text
stringlengths
1
1.05M
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // The following only applies to changes made to this file as part of YugaByte development. // // Portions Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #include "yb/consensus/consensus_queue.h" #include <algorithm> #include <mutex> #include <shared_mutex> #include <string> #include <utility> #include <boost/container/small_vector.hpp> #include <glog/logging.h> #include "yb/consensus/consensus_context.h" #include "yb/consensus/log_util.h" #include "yb/consensus/opid_util.h" #include "yb/consensus/quorum_util.h" #include "yb/consensus/raft_consensus.h" #include "yb/consensus/replicate_msgs_holder.h" #include "yb/gutil/bind.h" #include "yb/gutil/dynamic_annotations.h" #include "yb/gutil/map-util.h" #include "yb/gutil/stl_util.h" #include "yb/gutil/strings/substitute.h" #include "yb/util/enums.h" #include "yb/util/fault_injection.h" #include "yb/util/flag_tags.h" #include "yb/util/locks.h" #include "yb/util/logging.h" #include "yb/util/mem_tracker.h" #include "yb/util/metrics.h" #include "yb/util/monotime.h" #include "yb/util/random_util.h" #include "yb/util/result.h" #include "yb/util/size_literals.h" #include "yb/util/status_log.h" #include "yb/util/threadpool.h" #include "yb/util/tostring.h" #include "yb/util/url-coding.h" using namespace std::literals; using namespace yb::size_literals; DECLARE_uint64(rpc_max_message_size); // We expect that consensus_max_batch_size_bytes + 1_KB would be less than rpc_max_message_size. // Otherwise such batch would be rejected by RPC layer. DEFINE_uint64(consensus_max_batch_size_bytes, 4_MB, "The maximum per-tablet RPC batch size when updating peers."); TAG_FLAG(consensus_max_batch_size_bytes, advanced); TAG_FLAG(consensus_max_batch_size_bytes, runtime); DEFINE_int32(follower_unavailable_considered_failed_sec, 900, "Seconds that a leader is unable to successfully heartbeat to a " "follower after which the follower is considered to be failed and " "evicted from the config."); TAG_FLAG(follower_unavailable_considered_failed_sec, advanced); DEFINE_int32(consensus_inject_latency_ms_in_notifications, 0, "Injects a random sleep between 0 and this many milliseconds into " "asynchronous notifications from the consensus queue back to the " "consensus implementation."); TAG_FLAG(consensus_inject_latency_ms_in_notifications, hidden); TAG_FLAG(consensus_inject_latency_ms_in_notifications, unsafe); DEFINE_int32(cdc_checkpoint_opid_interval_ms, 60 * 1000, "Interval up to which CDC consumer's checkpoint is considered for retaining log cache." "If we haven't received an updated checkpoint from CDC consumer within the interval " "specified by cdc_checkpoint_opid_interval, then log cache does not consider that " "consumer while determining which op IDs to evict."); DEFINE_bool(enable_consensus_exponential_backoff, true, "Whether exponential backoff based on number of retransmissions at tablet leader " "for number of entries to replicate to lagging follower is enabled."); TAG_FLAG(enable_consensus_exponential_backoff, advanced); TAG_FLAG(enable_consensus_exponential_backoff, runtime); DEFINE_int32(consensus_lagging_follower_threshold, 10, "Number of retransmissions at tablet leader to mark a follower as lagging. " "-1 disables the feature."); TAG_FLAG(consensus_lagging_follower_threshold, advanced); TAG_FLAG(consensus_lagging_follower_threshold, runtime); DEFINE_test_flag(bool, disallow_lmp_failures, false, "Whether we disallow PRECEDING_ENTRY_DIDNT_MATCH failures for non new peers."); namespace { constexpr const auto kMinRpcThrottleThresholdBytes = 16; static bool RpcThrottleThresholdBytesValidator(const char* flagname, int64_t value) { if (value > 0) { if (value < kMinRpcThrottleThresholdBytes) { LOG(ERROR) << "Expect " << flagname << " to be at least " << kMinRpcThrottleThresholdBytes; return false; } else if (implicit_cast<size_t>(value) >= FLAGS_consensus_max_batch_size_bytes) { LOG(ERROR) << "Expect " << flagname << " to be less than consensus_max_batch_size_bytes " << "value (" << FLAGS_consensus_max_batch_size_bytes << ")"; return false; } } return true; } } // namespace DECLARE_int64(rpc_throttle_threshold_bytes); namespace yb { namespace consensus { using log::Log; using std::unique_ptr; using rpc::Messenger; using strings::Substitute; METRIC_DEFINE_gauge_int64(tablet, majority_done_ops, "Leader Operations Acked by Majority", MetricUnit::kOperations, "Number of operations in the leader queue ack'd by a majority but " "not all peers."); METRIC_DEFINE_gauge_int64(tablet, in_progress_ops, "Leader Operations in Progress", MetricUnit::kOperations, "Number of operations in the leader queue ack'd by a minority of " "peers."); const auto kCDCConsumerCheckpointInterval = FLAGS_cdc_checkpoint_opid_interval_ms * 1ms; std::string MajorityReplicatedData::ToString() const { return Format( "{ op_id: $0 leader_lease_expiration: $1 ht_lease_expiration: $2 num_sst_files: $3 }", op_id, leader_lease_expiration, ht_lease_expiration, num_sst_files); } std::string PeerMessageQueue::TrackedPeer::ToString() const { return Format( "{ peer: $0 is_new: $1 last_received: $2 next_index: $3 last_known_committed_idx: $4 " "is_last_exchange_successful: $5 needs_remote_bootstrap: $6 member_type: $7 " "num_sst_files: $8 last_applied: $9 }", uuid, is_new, last_received, next_index, last_known_committed_idx, is_last_exchange_successful, needs_remote_bootstrap, PeerMemberType_Name(member_type), num_sst_files, last_applied); } void PeerMessageQueue::TrackedPeer::ResetLeaderLeases() { leader_lease_expiration.Reset(); leader_ht_lease_expiration.Reset(); } void PeerMessageQueue::TrackedPeer::ResetLastRequest() { // Reset so that next transmission is not considered a re-transmission. last_num_messages_sent = -1; current_retransmissions = -1; } #define INSTANTIATE_METRIC(x) \ x.Instantiate(metric_entity, 0) PeerMessageQueue::Metrics::Metrics(const scoped_refptr<MetricEntity>& metric_entity) : num_majority_done_ops(INSTANTIATE_METRIC(METRIC_majority_done_ops)), num_in_progress_ops(INSTANTIATE_METRIC(METRIC_in_progress_ops)) { } #undef INSTANTIATE_METRIC PeerMessageQueue::PeerMessageQueue(const scoped_refptr<MetricEntity>& metric_entity, const scoped_refptr<log::Log>& log, const MemTrackerPtr& server_tracker, const MemTrackerPtr& parent_tracker, const RaftPeerPB& local_peer_pb, const string& tablet_id, const server::ClockPtr& clock, ConsensusContext* context, unique_ptr<ThreadPoolToken> raft_pool_token) : raft_pool_observers_token_(std::move(raft_pool_token)), local_peer_pb_(local_peer_pb), local_peer_uuid_(local_peer_pb_.has_permanent_uuid() ? local_peer_pb_.permanent_uuid() : string()), tablet_id_(tablet_id), log_cache_(metric_entity, log, server_tracker, local_peer_pb.permanent_uuid(), tablet_id), operations_mem_tracker_( MemTracker::FindOrCreateTracker("OperationsFromDisk", parent_tracker)), metrics_(metric_entity), clock_(clock), context_(context) { DCHECK(local_peer_pb_.has_permanent_uuid()); DCHECK(!local_peer_pb_.last_known_private_addr().empty()); } void PeerMessageQueue::Init(const OpId& last_locally_replicated) { LockGuard lock(queue_lock_); CHECK_EQ(queue_state_.state, State::kQueueConstructed); log_cache_.Init(last_locally_replicated.ToPB<OpIdPB>()); queue_state_.last_appended = last_locally_replicated; queue_state_.state = State::kQueueOpen; local_peer_ = TrackPeerUnlocked(local_peer_uuid_); if (context_) { context_->ListenNumSSTFilesChanged(std::bind(&PeerMessageQueue::NumSSTFilesChanged, this)); installed_num_sst_files_changed_listener_ = true; } } void PeerMessageQueue::SetLeaderMode(const OpId& committed_op_id, int64_t current_term, const OpId& last_applied_op_id, const RaftConfigPB& active_config) { LockGuard lock(queue_lock_); queue_state_.current_term = current_term; queue_state_.committed_op_id = committed_op_id; queue_state_.last_applied_op_id = last_applied_op_id; queue_state_.majority_replicated_op_id = committed_op_id; queue_state_.active_config.reset(new RaftConfigPB(active_config)); CHECK(IsRaftConfigVoter(local_peer_uuid_, *queue_state_.active_config)) << local_peer_pb_.ShortDebugString() << " not a voter in config: " << queue_state_.active_config->ShortDebugString(); queue_state_.majority_size_ = MajoritySize(CountVoters(*queue_state_.active_config)); queue_state_.mode = Mode::LEADER; LOG_WITH_PREFIX_UNLOCKED(INFO) << "Queue going to LEADER mode. State: " << queue_state_.ToString(); CheckPeersInActiveConfigIfLeaderUnlocked(); // Reset last communication time with all peers to reset the clock on the // failure timeout. MonoTime now(MonoTime::Now()); for (const PeersMap::value_type& entry : peers_map_) { entry.second->ResetLeaderLeases(); entry.second->last_successful_communication_time = now; } } void PeerMessageQueue::SetNonLeaderMode() { LockGuard lock(queue_lock_); queue_state_.active_config.reset(); queue_state_.mode = Mode::NON_LEADER; queue_state_.majority_size_ = -1; LOG_WITH_PREFIX_UNLOCKED(INFO) << "Queue going to NON_LEADER mode. State: " << queue_state_.ToString(); } void PeerMessageQueue::TrackPeer(const string& uuid) { LockGuard lock(queue_lock_); TrackPeerUnlocked(uuid); } PeerMessageQueue::TrackedPeer* PeerMessageQueue::TrackPeerUnlocked(const string& uuid) { CHECK(!uuid.empty()) << "Got request to track peer with empty UUID"; DCHECK_EQ(queue_state_.state, State::kQueueOpen); TrackedPeer* tracked_peer = new TrackedPeer(uuid); // We don't know the last operation received by the peer so, following the Raft protocol, we set // next_index to one past the end of our own log. This way, if calling this method is the result // of a successful leader election and the logs between the new leader and remote peer match, the // peer->next_index will point to the index of the soon-to-be-written NO_OP entry that is used to // assert leadership. If we guessed wrong, and the peer does not have a log that matches ours, the // normal queue negotiation process will eventually find the right point to resume from. tracked_peer->next_index = queue_state_.last_appended.index + 1; InsertOrDie(&peers_map_, uuid, tracked_peer); CheckPeersInActiveConfigIfLeaderUnlocked(); // We don't know how far back this peer is, so set the all replicated watermark to // MinimumOpId. We'll advance it when we know how far along the peer is. queue_state_.all_replicated_op_id = OpId::Min(); return tracked_peer; } void PeerMessageQueue::UntrackPeer(const string& uuid) { LockGuard lock(queue_lock_); TrackedPeer* peer = EraseKeyReturnValuePtr(&peers_map_, uuid); if (peer != nullptr) { delete peer; } } void PeerMessageQueue::CheckPeersInActiveConfigIfLeaderUnlocked() const { if (queue_state_.mode != Mode::LEADER) return; std::unordered_set<std::string> config_peer_uuids; for (const RaftPeerPB& peer_pb : queue_state_.active_config->peers()) { InsertOrDie(&config_peer_uuids, peer_pb.permanent_uuid()); } for (const PeersMap::value_type& entry : peers_map_) { if (!ContainsKey(config_peer_uuids, entry.first)) { LOG_WITH_PREFIX_UNLOCKED(FATAL) << Substitute("Peer $0 is not in the active config. " "Queue state: $1", entry.first, queue_state_.ToString()); } } } void PeerMessageQueue::NumSSTFilesChanged() { auto num_sst_files = context_->NumSSTFiles(); uint64_t majority_replicated_num_sst_files; { LockGuard lock(queue_lock_); if (queue_state_.mode != Mode::LEADER) { return; } auto it = peers_map_.find(local_peer_uuid_); if (it == peers_map_.end()) { return; } it->second->num_sst_files = num_sst_files; majority_replicated_num_sst_files = NumSSTFilesWatermark(); } NotifyObservers( "majority replicated num SST files changed", [majority_replicated_num_sst_files](PeerMessageQueueObserver* observer) { observer->MajorityReplicatedNumSSTFilesChanged(majority_replicated_num_sst_files); }); } void PeerMessageQueue::LocalPeerAppendFinished(const OpId& id, const Status& status) { CHECK_OK(status); // Fake an RPC response from the local peer. // TODO: we should probably refactor the ResponseFromPeer function so that we don't need to // construct this fake response, but this seems to work for now. ConsensusResponsePB fake_response; id.ToPB(fake_response.mutable_status()->mutable_last_received()); id.ToPB(fake_response.mutable_status()->mutable_last_received_current_leader()); if (context_) { fake_response.set_num_sst_files(context_->NumSSTFiles()); } { LockGuard lock(queue_lock_); // TODO This ugly fix is required because we unlock queue_lock_ while doing AppendOperations. // So LocalPeerAppendFinished could be invoked before rest of AppendOperations. if (queue_state_.last_appended.index < id.index) { queue_state_.last_appended = id; } fake_response.mutable_status()->set_last_committed_idx(queue_state_.committed_op_id.index); queue_state_.last_applied_op_id.ToPB(fake_response.mutable_status()->mutable_last_applied()); if (queue_state_.mode != Mode::LEADER) { log_cache_.EvictThroughOp(id.index); UpdateMetrics(); return; } } ResponseFromPeer(local_peer_uuid_, fake_response); } Status PeerMessageQueue::TEST_AppendOperation(const ReplicateMsgPtr& msg) { return AppendOperations( { msg }, yb::OpId::FromPB(msg->committed_op_id()), RestartSafeCoarseMonoClock().Now()); } Status PeerMessageQueue::AppendOperations(const ReplicateMsgs& msgs, const yb::OpId& committed_op_id, RestartSafeCoarseTimePoint batch_mono_time) { DFAKE_SCOPED_LOCK(append_fake_lock_); OpId last_id; if (!msgs.empty()) { std::unique_lock<simple_spinlock> lock(queue_lock_); last_id = OpId::FromPB(msgs.back()->id()); if (last_id.term > queue_state_.current_term) { queue_state_.current_term = last_id.term; } } else { std::unique_lock<simple_spinlock> lock(queue_lock_); last_id = queue_state_.last_appended; } // Unlock ourselves during Append to prevent a deadlock: it's possible that the log buffer is // full, in which case AppendOperations would block. However, for the log buffer to empty, it may // need to call LocalPeerAppendFinished() which also needs queue_lock_. // // Since we are doing AppendOperations only in one thread, no concurrent AppendOperations could // be executed and queue_state_.last_appended will be updated correctly. RETURN_NOT_OK(log_cache_.AppendOperations( msgs, committed_op_id, batch_mono_time, Bind(&PeerMessageQueue::LocalPeerAppendFinished, Unretained(this), last_id))); if (!msgs.empty()) { std::unique_lock<simple_spinlock> lock(queue_lock_); queue_state_.last_appended = last_id; UpdateMetrics(); } return Status::OK(); } uint64_t GetNumMessagesToSendWithBackoff(int64_t last_num_messages_sent) { return std::max<int64_t>((last_num_messages_sent >> 1) - 1, 0); } Status PeerMessageQueue::RequestForPeer(const string& uuid, ConsensusRequestPB* request, ReplicateMsgsHolder* msgs_holder, bool* needs_remote_bootstrap, PeerMemberType* member_type, bool* last_exchange_successful) { static constexpr uint64_t kSendUnboundedLogOps = std::numeric_limits<uint64_t>::max(); DCHECK(request->ops().empty()) << request->ShortDebugString(); OpId preceding_id; MonoDelta unreachable_time = MonoDelta::kMin; bool is_voter = false; bool is_new; int64_t previously_sent_index; uint64_t num_log_ops_to_send; HybridTime propagated_safe_time; // Should be before now_ht, i.e. not greater than propagated_hybrid_time. if (context_) { propagated_safe_time = VERIFY_RESULT(context_->PreparePeerRequest()); } { LockGuard lock(queue_lock_); DCHECK_EQ(queue_state_.state, State::kQueueOpen); DCHECK_NE(uuid, local_peer_uuid_); auto peer = FindPtrOrNull(peers_map_, uuid); if (PREDICT_FALSE(peer == nullptr || queue_state_.mode == Mode::NON_LEADER)) { return STATUS(NotFound, "Peer not tracked or queue not in leader mode."); } HybridTime now_ht; is_new = peer->is_new; if (!is_new) { now_ht = clock_->Now(); auto ht_lease_expiration_micros = now_ht.GetPhysicalValueMicros() + FLAGS_ht_lease_duration_ms * 1000; auto leader_lease_duration_ms = GetAtomicFlag(&FLAGS_leader_lease_duration_ms); request->set_leader_lease_duration_ms(leader_lease_duration_ms); request->set_ht_lease_expiration(ht_lease_expiration_micros); // As noted here: // https://red.ht/2sCSErb // // The _COARSE variants are faster to read and have a precision (also known as resolution) of // one millisecond (ms). // // Coarse clock precision is 1 millisecond. const auto kCoarseClockPrecision = 1ms; // Because of coarse clocks we subtract 2ms, to be sure that our local version of lease // does not expire after it expires at follower. peer->leader_lease_expiration.last_sent = CoarseMonoClock::Now() + leader_lease_duration_ms * 1ms - kCoarseClockPrecision * 2; peer->leader_ht_lease_expiration.last_sent = ht_lease_expiration_micros; } else { now_ht = clock_->Now(); request->clear_leader_lease_duration_ms(); request->clear_ht_lease_expiration(); peer->leader_lease_expiration.Reset(); peer->leader_ht_lease_expiration.Reset(); } // This is initialized to the queue's last appended op but gets set to the id of the // log entry preceding the first one in 'messages' if messages are found for the peer. // // The leader does not know the actual state of a peer but it should always send a value of // preceding_id that is present in the leader's own log, so the follower can verify the log // matching property. // // In case we decide not to send any messages to the follower this time due to exponential // backoff to an unresponsive follower, we will keep preceding_id equal to last_appended. // This is safe because unless the follower already has that operation, it will fail to find // it in its pending operations in EnforceLogMatchingPropertyMatchesUnlocked and will return // a log matching property violation error without applying any incorrect messages from its log. // // See this scenario for more context on the issue we are trying to avoid: // https://github.com/yugabyte/yugabyte-db/issues/8150#issuecomment-827821784 preceding_id = queue_state_.last_appended; request->set_propagated_hybrid_time(now_ht.ToUint64()); // NOTE: committed_op_id may be overwritten later. // In our system committed_op_id means that this operation was also applied. // If we have operation that applied significant time, followers would not know that this // operation is committed until it is applied in the leader. // To address this issue we use majority_replicated_op_id, that is updated before apply. // But we could use it only when its term matches current term, see Fig.8 in Raft paper. if (queue_state_.majority_replicated_op_id.index > queue_state_.committed_op_id.index && queue_state_.majority_replicated_op_id.term == queue_state_.current_term) { queue_state_.majority_replicated_op_id.ToPB(request->mutable_committed_op_id()); } else { queue_state_.committed_op_id.ToPB(request->mutable_committed_op_id()); } request->set_caller_term(queue_state_.current_term); unreachable_time = MonoTime::Now().GetDeltaSince(peer->last_successful_communication_time); if (member_type) *member_type = peer->member_type; if (last_exchange_successful) *last_exchange_successful = peer->is_last_exchange_successful; *needs_remote_bootstrap = peer->needs_remote_bootstrap; previously_sent_index = peer->next_index - 1; if (FLAGS_enable_consensus_exponential_backoff && peer->last_num_messages_sent >= 0) { // Previous request to peer has not been acked. Reduce number of entries to be sent // in this attempt using exponential backoff. Note that to_index is inclusive. num_log_ops_to_send = GetNumMessagesToSendWithBackoff(peer->last_num_messages_sent); } else { // Previous request to peer has been acked or a heartbeat response has been received. // Transmit as many entries as allowed. num_log_ops_to_send = kSendUnboundedLogOps; } peer->current_retransmissions++; if (peer->member_type == PeerMemberType::VOTER) { is_voter = true; } } if (unreachable_time.ToSeconds() > FLAGS_follower_unavailable_considered_failed_sec) { if (!is_voter || CountVoters(*queue_state_.active_config) > 2) { // We never drop from 2 voters to 1 voter automatically, at least for now (12/4/18). We may // want to revisit this later, we're just being cautious with this. // We remove unconditionally any failed non-voter replica (PRE_VOTER, PRE_OBSERVER, OBSERVER). string msg = Substitute("Leader has been unable to successfully communicate " "with Peer $0 for more than $1 seconds ($2)", uuid, FLAGS_follower_unavailable_considered_failed_sec, unreachable_time.ToString()); NotifyObserversOfFailedFollower(uuid, queue_state_.current_term, msg); } } if (PREDICT_FALSE(*needs_remote_bootstrap)) { YB_LOG_WITH_PREFIX_UNLOCKED_EVERY_N_SECS(INFO, 30) << "Peer needs remote bootstrap: " << uuid; return Status::OK(); } *needs_remote_bootstrap = false; request->clear_propagated_safe_time(); // If we've never communicated with the peer, we don't know what messages to send, so we'll send a // status-only request. If the peer has not responded to the point that our to_index == next_index // due to exponential backoff of replicated segment size, we also send a status-only request. // Otherwise, we grab requests from the log starting at the last_received point. if (!is_new && num_log_ops_to_send > 0) { // The batch of messages to send to the peer. auto max_batch_size = FLAGS_consensus_max_batch_size_bytes - request->ByteSizeLong(); auto to_index = num_log_ops_to_send == kSendUnboundedLogOps ? 0 : previously_sent_index + num_log_ops_to_send; auto result = ReadFromLogCache(previously_sent_index, to_index, max_batch_size, uuid); if (PREDICT_FALSE(!result.ok())) { if (PREDICT_TRUE(result.status().IsNotFound())) { std::string msg = Format("The logs necessary to catch up peer $0 have been " "garbage collected. The follower will never be able " "to catch up ($1)", uuid, result.status()); NotifyObserversOfFailedFollower(uuid, queue_state_.current_term, msg); } return result.status(); } preceding_id = result->preceding_op; // We use AddAllocated rather than copy, because we pin the log cache at the "all replicated" // point. At some point we may want to allow partially loading (and not pinning) earlier // messages. At that point we'll need to do something smarter here, like copy or ref-count. for (const auto& msg : result->messages) { request->mutable_ops()->AddAllocated(msg.get()); } { LockGuard lock(queue_lock_); auto peer = FindPtrOrNull(peers_map_, uuid); if (PREDICT_FALSE(peer == nullptr)) { return STATUS(NotFound, "Peer not tracked."); } peer->last_num_messages_sent = result->messages.size(); } ScopedTrackedConsumption consumption; if (result->read_from_disk_size) { consumption = ScopedTrackedConsumption(operations_mem_tracker_, result->read_from_disk_size); } *msgs_holder = ReplicateMsgsHolder( request->mutable_ops(), std::move(result->messages), std::move(consumption)); if (propagated_safe_time && !result->have_more_messages && num_log_ops_to_send == kSendUnboundedLogOps) { // Get the current local safe time on the leader and propagate it to the follower. request->set_propagated_safe_time(propagated_safe_time.ToUint64()); } } preceding_id.ToPB(request->mutable_preceding_id()); // All entries committed at leader may not be available at lagging follower. // `commited_op_id` in this request may make a lagging follower aware of the // highest committed op index at the leader. We have a sanity check during tablet // bootstrap, in TabletBootstrap::PlaySegments(), that this tablet did not lose a // committed operation. Hence avoid sending a committed op id that is too large // to such a lagging follower. // If we send operations to it, then last know operation to this follower will be last sent // operation. If we don't send any operation, then last known operation will be preceding // operation. // We don't have to change committed_op_id when it is less than max_allowed_committed_op_id, // because it will have actual committed_op_id value and this operation is known to the // follower. const auto max_allowed_committed_op_id = !request->ops().empty() ? OpId::FromPB(request->ops().rbegin()->id()) : preceding_id; if (max_allowed_committed_op_id.index < request->committed_op_id().index()) { max_allowed_committed_op_id.ToPB(request->mutable_committed_op_id()); } if (PREDICT_FALSE(VLOG_IS_ON(2))) { if (request->ops_size() > 0) { VLOG_WITH_PREFIX_UNLOCKED(2) << "Sending request with operations to Peer: " << uuid << ". Size: " << request->ops_size() << ". From: " << request->ops(0).id().ShortDebugString() << ". To: " << request->ops(request->ops_size() - 1).id().ShortDebugString(); VLOG_WITH_PREFIX_UNLOCKED(3) << "Operations: " << yb::ToString(request->ops()); } else { VLOG_WITH_PREFIX_UNLOCKED(2) << "Sending " << (is_new ? "new " : "") << "status only request to Peer: " << uuid << ": " << request->ShortDebugString(); } } return Status::OK(); } Result<ReadOpsResult> PeerMessageQueue::ReadFromLogCache(int64_t after_index, int64_t to_index, size_t max_batch_size, const std::string& peer_uuid, const CoarseTimePoint deadline) { DCHECK_LT(FLAGS_consensus_max_batch_size_bytes + 1_KB, FLAGS_rpc_max_message_size); // We try to get the follower's next_index from our log. // Note this is not using "term" and needs to change auto result = log_cache_.ReadOps(after_index, to_index, max_batch_size, deadline); if (PREDICT_FALSE(!result.ok())) { auto s = result.status(); if (PREDICT_TRUE(s.IsNotFound())) { return s; } else if (s.IsIncomplete()) { // IsIncomplete() means that we tried to read beyond the head of the log (in the future). // KUDU-1078 points to a fix of this log spew issue that we've ported. This should not // happen under normal circumstances. LOG_WITH_PREFIX_UNLOCKED(ERROR) << "Error trying to read ahead of the log " << "while preparing peer request: " << s.ToString() << ". Destination peer: " << peer_uuid; return s; } else { LOG_WITH_PREFIX_UNLOCKED(FATAL) << "Error reading the log while preparing peer request: " << s.ToString() << ". Destination peer: " << peer_uuid; return s; } } return result; } // Read majority replicated messages from cache for CDC. // CDC producer will use this to get the messages to send in response to cdc::GetChanges RPC. Result<ReadOpsResult> PeerMessageQueue::ReadReplicatedMessagesForCDC( const yb::OpId& last_op_id, int64_t* repl_index, const CoarseTimePoint deadline) { // The batch of messages read from cache. int64_t to_index; bool pending_messages = false; { LockGuard lock(queue_lock_); // Use committed_op_id because it's already been processed by the Transaction codepath. to_index = queue_state_.committed_op_id.index; // Determine if there are pending operations in RAFT but not yet LogCache. pending_messages = to_index != queue_state_.majority_replicated_op_id.index; } if (repl_index) { *repl_index = to_index; } if (last_op_id.index >= to_index) { // Nothing to read. return ReadOpsResult(); } // If an empty OpID is only sent on the first read request, start at the earliest known entry. int64_t after_op_index = last_op_id.empty() ? max(log_cache_.earliest_op_index(), last_op_id.index) : last_op_id.index; auto result = ReadFromLogCache( after_op_index, to_index, FLAGS_consensus_max_batch_size_bytes, local_peer_uuid_, deadline); if (PREDICT_FALSE(!result.ok()) && PREDICT_TRUE(result.status().IsNotFound())) { LOG_WITH_PREFIX_UNLOCKED(INFO) << Format( "The logs from index $0 have been garbage collected and cannot be read ($1)", after_op_index, result.status()); } if (result.ok()) { result->have_more_messages |= pending_messages; } return result; } Status PeerMessageQueue::GetRemoteBootstrapRequestForPeer(const string& uuid, StartRemoteBootstrapRequestPB* req) { TrackedPeer* peer = nullptr; { LockGuard lock(queue_lock_); DCHECK_EQ(queue_state_.state, State::kQueueOpen); DCHECK_NE(uuid, local_peer_uuid_); peer = FindPtrOrNull(peers_map_, uuid); if (PREDICT_FALSE(peer == nullptr || queue_state_.mode == Mode::NON_LEADER)) { return STATUS(NotFound, "Peer not tracked or queue not in leader mode."); } } if (PREDICT_FALSE(!peer->needs_remote_bootstrap)) { return STATUS(IllegalState, "Peer does not need to remotely bootstrap", uuid); } if (peer->member_type == PeerMemberType::VOTER || peer->member_type == PeerMemberType::OBSERVER) { LOG(INFO) << "Remote bootstrapping peer " << uuid << " with type " << PeerMemberType_Name(peer->member_type); } req->Clear(); req->set_dest_uuid(uuid); req->set_tablet_id(tablet_id_); req->set_bootstrap_peer_uuid(local_peer_uuid_); *req->mutable_source_private_addr() = local_peer_pb_.last_known_private_addr(); *req->mutable_source_broadcast_addr() = local_peer_pb_.last_known_broadcast_addr(); *req->mutable_source_cloud_info() = local_peer_pb_.cloud_info(); req->set_caller_term(queue_state_.current_term); peer->needs_remote_bootstrap = false; // Now reset the flag. return Status::OK(); } void PeerMessageQueue::UpdateCDCConsumerOpId(const yb::OpId& op_id) { std::lock_guard<rw_spinlock> l(cdc_consumer_lock_); cdc_consumer_op_id_ = op_id; cdc_consumer_op_id_last_updated_ = CoarseMonoClock::Now(); } yb::OpId PeerMessageQueue::GetCDCConsumerOpIdToEvict() { std::shared_lock<rw_spinlock> l(cdc_consumer_lock_); // For log cache eviction, we only want to include CDC consumers that are actively polling. // If CDC consumer checkpoint has not been updated recently, we exclude it. if (CoarseMonoClock::Now() - cdc_consumer_op_id_last_updated_ <= kCDCConsumerCheckpointInterval) { return cdc_consumer_op_id_; } else { return yb::OpId::Max(); } } void PeerMessageQueue::UpdateAllReplicatedOpId(OpId* result) { OpId new_op_id = OpId::Max(); for (const auto& peer : peers_map_) { if (!peer.second->is_last_exchange_successful) { return; } if (peer.second->last_received.index < new_op_id.index) { new_op_id = peer.second->last_received; } } CHECK_NE(OpId::Max(), new_op_id); *result = new_op_id; } void PeerMessageQueue::UpdateAllAppliedOpId(OpId* result) { OpId all_applied_op_id = OpId::Max(); for (const auto& peer : peers_map_) { if (!peer.second->is_last_exchange_successful) { return; } all_applied_op_id = std::min(all_applied_op_id, peer.second->last_applied); } CHECK_NE(OpId::Max(), all_applied_op_id); *result = all_applied_op_id; } void PeerMessageQueue::UpdateAllNonLaggingReplicatedOpId(int32_t threshold) { OpId new_op_id = OpId::Max(); for (const auto& peer : peers_map_) { // Ignore lagging follower. if (peer.second->current_retransmissions >= threshold) { continue; } if (peer.second->last_received.index < new_op_id.index) { new_op_id = peer.second->last_received; } } if (new_op_id == OpId::Max()) { LOG_WITH_PREFIX_UNLOCKED(INFO) << "Non lagging peer(s) not found."; new_op_id = queue_state_.all_replicated_op_id; } if (queue_state_.all_nonlagging_replicated_op_id.index < new_op_id.index) { queue_state_.all_nonlagging_replicated_op_id = new_op_id; } } HAS_MEMBER_FUNCTION(InfiniteWatermarkForLocalPeer); template <class Policy, bool HasMemberFunction_InfiniteWatermarkForLocalPeer> struct GetInfiniteWatermarkForLocalPeer; template <class Policy> struct GetInfiniteWatermarkForLocalPeer<Policy, true> { static auto Apply() { return Policy::InfiniteWatermarkForLocalPeer(); } }; template <class Policy> struct GetInfiniteWatermarkForLocalPeer<Policy, false> { // Should not be invoked, but have to define to make compiler happy. static typename Policy::result_type Apply() { LOG(DFATAL) << "Invoked Apply when InfiniteWatermarkForLocalPeer is not defined"; return typename Policy::result_type(); } }; template <class Policy> typename Policy::result_type PeerMessageQueue::GetWatermark() { DCHECK(queue_lock_.is_locked()); const auto num_peers_required = queue_state_.majority_size_; if (num_peers_required == kUninitializedMajoritySize) { // We don't even know the quorum majority size yet. return Policy::NotEnoughPeersValue(); } CHECK_GE(num_peers_required, 0); const ssize_t num_peers = peers_map_.size(); if (num_peers < num_peers_required) { return Policy::NotEnoughPeersValue(); } // This flag indicates whether to implicitly assume that the local peer has an "infinite" // replicated value of the dimension that we are computing a watermark for. There is a difference // in logic between handling of OpIds vs. leader leases: // - For OpIds, the local peer might actually be less up-to-date than followers. // - For leader leases, we always assume that we've replicated an "infinite" lease to ourselves. const bool local_peer_infinite_watermark = HasMemberFunction_InfiniteWatermarkForLocalPeer<Policy>::value; if (num_peers_required == 1 && local_peer_infinite_watermark) { // We give "infinite lease" to ourselves. return GetInfiniteWatermarkForLocalPeer< Policy, HasMemberFunction_InfiniteWatermarkForLocalPeer<Policy>::value>::Apply(); } constexpr size_t kMaxPracticalReplicationFactor = 5; boost::container::small_vector< typename Policy::result_type, kMaxPracticalReplicationFactor> watermarks; watermarks.reserve(num_peers - 1 + !local_peer_infinite_watermark); for (const PeersMap::value_type &peer_map_entry : peers_map_) { const TrackedPeer &peer = *peer_map_entry.second; if (local_peer_infinite_watermark && peer.uuid == local_peer_uuid_) { // Don't even include the local peer in the watermarks array. Assume it has an "infinite" // value of the watermark. continue; } if (!IsRaftConfigVoter(peer.uuid, *queue_state_.active_config)) { // Only votes from VOTERs in the active config should be taken into consideration continue; } if (peer.is_last_exchange_successful) { watermarks.push_back(Policy::ExtractValue(peer)); } } // We always assume that local peer has most recent information. const ssize_t num_responsive_peers = watermarks.size() + local_peer_infinite_watermark; if (num_responsive_peers < num_peers_required) { VLOG_WITH_PREFIX_UNLOCKED(2) << Policy::Name() << " watermarks by peer: " << ::yb::ToString(watermarks) << ", num_peers_required=" << num_peers_required << ", num_responsive_peers=" << num_responsive_peers << ", not enough responsive peers"; // There are not enough peers with which the last message exchange was successful. return Policy::NotEnoughPeersValue(); } // If there are 5 peers (and num_peers_required is 3), and we have successfully replicated // something to 3 of them and 4th is our local peer, there are two possibilities: // - If local_peer_infinite_watermark is false (for OpId): watermarks.size() is 4, // and we want an OpId value such that 3 or more peers have replicated that or greater value. // Then index_of_interest = 1, computed as watermarks.size() - num_peers_required, or // num_responsive_peers - num_peers_required. // // - If local_peer_infinite_watermark is true (for leader leases): watermarks.size() is 3, and we // are assuming that the local peer (leader) has replicated an infinitely high watermark to // itself. Then watermark.size() is 3 (because we skip the local peer when populating // watermarks), but num_responsive_peers is still 4, and the expression stays the same. const size_t index_of_interest = num_responsive_peers - num_peers_required; DCHECK_LT(index_of_interest, watermarks.size()); auto nth = watermarks.begin() + index_of_interest; std::nth_element(watermarks.begin(), nth, watermarks.end(), typename Policy::Comparator()); VLOG_WITH_PREFIX_UNLOCKED(2) << Policy::Name() << " watermarks by peer: " << ::yb::ToString(watermarks) << ", num_peers_required=" << num_peers_required << ", local_peer_infinite_watermark=" << local_peer_infinite_watermark << ", watermark: " << yb::ToString(*nth); return *nth; } CoarseTimePoint PeerMessageQueue::LeaderLeaseExpirationWatermark() { struct Policy { typedef CoarseTimePoint result_type; // Workaround for a gcc bug. That does not understand that Comparator is actually being used. __attribute__((unused)) typedef std::less<result_type> Comparator; static result_type NotEnoughPeersValue() { return result_type::min(); } static result_type InfiniteWatermarkForLocalPeer() { return result_type::max(); } static result_type ExtractValue(const TrackedPeer& peer) { auto lease_exp = peer.leader_lease_expiration.last_received; return lease_exp != CoarseTimePoint() ? lease_exp : CoarseTimePoint::min(); } static const char* Name() { return "Leader lease expiration"; } }; return GetWatermark<Policy>(); } MicrosTime PeerMessageQueue::HybridTimeLeaseExpirationWatermark() { struct Policy { typedef MicrosTime result_type; // Workaround for a gcc bug. That does not understand that Comparator is actually being used. __attribute__((unused)) typedef std::less<result_type> Comparator; static result_type NotEnoughPeersValue() { return HybridTime::kMin.GetPhysicalValueMicros(); } static result_type InfiniteWatermarkForLocalPeer() { return HybridTime::kMax.GetPhysicalValueMicros(); } static result_type ExtractValue(const TrackedPeer& peer) { return peer.leader_ht_lease_expiration.last_received; } static const char* Name() { return "Hybrid time leader lease expiration"; } }; return GetWatermark<Policy>(); } uint64_t PeerMessageQueue::NumSSTFilesWatermark() { struct Policy { typedef uint64_t result_type; // Workaround for a gcc bug. That does not understand that Comparator is actually being used. __attribute__((unused)) typedef std::greater<result_type> Comparator; static result_type NotEnoughPeersValue() { return 0; } static result_type ExtractValue(const TrackedPeer& peer) { return peer.num_sst_files; } static const char* Name() { return "Num SST files"; } }; auto watermark = GetWatermark<Policy>(); return std::max(watermark, local_peer_->num_sst_files); } OpId PeerMessageQueue::OpIdWatermark() { struct Policy { typedef OpId result_type; static result_type NotEnoughPeersValue() { return OpId::Min(); } static result_type ExtractValue(const TrackedPeer& peer) { return peer.last_received; } struct Comparator { bool operator()(const OpId& lhs, const OpId& rhs) { return lhs.index < rhs.index; } }; static const char* Name() { return "OpId"; } }; return GetWatermark<Policy>(); } void PeerMessageQueue::NotifyPeerIsResponsiveDespiteError(const std::string& peer_uuid) { LockGuard l(queue_lock_); TrackedPeer* peer = FindPtrOrNull(peers_map_, peer_uuid); if (!peer) return; peer->last_successful_communication_time = MonoTime::Now(); } void PeerMessageQueue::RequestWasNotSent(const std::string& peer_uuid) { LockGuard scoped_lock(queue_lock_); DCHECK_NE(State::kQueueConstructed, queue_state_.state); TrackedPeer* peer = FindPtrOrNull(peers_map_, peer_uuid); if (PREDICT_FALSE(queue_state_.state != State::kQueueOpen || peer == nullptr)) { LOG_WITH_PREFIX_UNLOCKED(WARNING) << "Queue is closed or peer was untracked."; return; } peer->ResetLastRequest(); } bool PeerMessageQueue::ResponseFromPeer(const std::string& peer_uuid, const ConsensusResponsePB& response) { DCHECK(response.IsInitialized()) << "Error: Uninitialized: " << response.InitializationErrorString() << ". Response: " << response.ShortDebugString(); MajorityReplicatedData majority_replicated; Mode mode_copy; bool result = false; { LockGuard scoped_lock(queue_lock_); DCHECK_NE(State::kQueueConstructed, queue_state_.state); TrackedPeer* peer = FindPtrOrNull(peers_map_, peer_uuid); if (PREDICT_FALSE(queue_state_.state != State::kQueueOpen || peer == nullptr)) { LOG_WITH_PREFIX_UNLOCKED(WARNING) << "Queue is closed or peer was untracked, disregarding " "peer response. Response: " << response.ShortDebugString(); return false; } // Remotely bootstrap the peer if the tablet is not found or deleted. if (response.has_error()) { // We only let special types of errors through to this point from the peer. CHECK_EQ(tserver::TabletServerErrorPB::TABLET_NOT_FOUND, response.error().code()) << response.ShortDebugString(); peer->needs_remote_bootstrap = true; // Since we received a response from the peer, we know it is alive. So we need to update // peer->last_successful_communication_time, otherwise, we will remove this peer from the // configuration if the remote bootstrap is not completed within // FLAGS_follower_unavailable_considered_failed_sec seconds. peer->last_successful_communication_time = MonoTime::Now(); YB_LOG_WITH_PREFIX_UNLOCKED_EVERY_N_SECS(INFO, 30) << "Marked peer as needing remote bootstrap: " << peer->ToString(); return true; } if (queue_state_.active_config) { RaftPeerPB peer_pb; if (!GetRaftConfigMember(*queue_state_.active_config, peer_uuid, &peer_pb).ok()) { LOG(FATAL) << "Peer " << peer_uuid << " not in active config"; } peer->member_type = peer_pb.member_type(); } else { peer->member_type = PeerMemberType::UNKNOWN_MEMBER_TYPE; } // Application level errors should be handled elsewhere DCHECK(!response.has_error()); // Take a snapshot of the current peer status. TrackedPeer previous = *peer; // Update the peer status based on the response. peer->is_new = false; peer->last_successful_communication_time = MonoTime::Now(); peer->ResetLastRequest(); if (response.has_status()) { const auto& status = response.status(); // Sanity checks. Some of these can be eventually removed, but they are handy for now. DCHECK(status.IsInitialized()) << "Error: Uninitialized: " << response.InitializationErrorString() << ". Response: " << response.ShortDebugString(); // The status must always have a last received op id and a last committed index. DCHECK(status.has_last_received()); DCHECK(status.has_last_received_current_leader()); DCHECK(status.has_last_committed_idx()); peer->last_known_committed_idx = status.last_committed_idx(); peer->last_applied = OpId::FromPB(status.last_applied()); // If the reported last-received op for the replica is in our local log, then resume sending // entries from that point onward. Otherwise, resume after the last op they received from us. // If we've never successfully sent them anything, start after the last-committed op in their // log, which is guaranteed by the Raft protocol to be a valid op. bool peer_has_prefix_of_log = IsOpInLog(yb::OpId::FromPB(status.last_received())); if (peer_has_prefix_of_log) { // If the latest thing in their log is in our log, we are in sync. peer->last_received = OpId::FromPB(status.last_received()); peer->next_index = peer->last_received.index + 1; } else if (!OpIdEquals(status.last_received_current_leader(), MinimumOpId())) { // Their log may have diverged from ours, however we are in the process of replicating our // ops to them, so continue doing so. Eventually, we will cause the divergent entry in their // log to be overwritten. peer->last_received = OpId::FromPB(status.last_received_current_leader()); peer->next_index = peer->last_received.index + 1; } else { // The peer is divergent and they have not (successfully) received anything from us yet. // Start sending from their last committed index. This logic differs from the Raft spec // slightly because instead of stepping back one-by-one from the end until we no longer have // an LMP error, we jump back to the last committed op indicated by the peer with the hope // that doing so will result in a faster catch-up process. DCHECK_GE(peer->last_known_committed_idx, 0); peer->next_index = peer->last_known_committed_idx + 1; } if (PREDICT_FALSE(status.has_error())) { peer->is_last_exchange_successful = false; switch (status.error().code()) { case ConsensusErrorPB::PRECEDING_ENTRY_DIDNT_MATCH: { DCHECK(status.has_last_received()); if (previous.is_new) { // That's currently how we can detect that we able to connect to a peer. LOG_WITH_PREFIX_UNLOCKED(INFO) << "Connected to new peer: " << peer->ToString(); } else { LOG_WITH_PREFIX_UNLOCKED(INFO) << "Got LMP mismatch error from peer: " << peer->ToString(); CHECK(!FLAGS_TEST_disallow_lmp_failures); } return true; } case ConsensusErrorPB::INVALID_TERM: { CHECK(response.has_responder_term()); LOG_WITH_PREFIX_UNLOCKED(INFO) << "Peer responded invalid term: " << peer->ToString() << ". Peer's new term: " << response.responder_term(); NotifyObserversOfTermChange(response.responder_term()); return false; } default: { LOG_WITH_PREFIX_UNLOCKED(FATAL) << "Unexpected consensus error. Code: " << ConsensusErrorPB::Code_Name(status.error().code()) << ". Response: " << response.ShortDebugString(); } } } } peer->is_last_exchange_successful = true; peer->num_sst_files = response.num_sst_files(); if (response.has_responder_term()) { // The peer must have responded with a term that is greater than or equal to the last known // term for that peer. peer->CheckMonotonicTerms(response.responder_term()); // If the responder didn't send an error back that must mean that it has a term that is the // same or lower than ours. CHECK_LE(response.responder_term(), queue_state_.current_term); } if (PREDICT_FALSE(VLOG_IS_ON(2))) { VLOG_WITH_PREFIX_UNLOCKED(2) << "Received Response from Peer (" << peer->ToString() << "). " << "Response: " << response.ShortDebugString(); } // If our log has the next request for the peer or if the peer's committed index is lower than // our own, set 'more_pending' to true. result = log_cache_.HasOpBeenWritten(peer->next_index) || (peer->last_known_committed_idx < queue_state_.committed_op_id.index); mode_copy = queue_state_.mode; if (mode_copy == Mode::LEADER) { auto new_majority_replicated_opid = OpIdWatermark(); if (new_majority_replicated_opid != OpId::Min()) { if (new_majority_replicated_opid.index == MaximumOpId().index()) { queue_state_.majority_replicated_op_id = local_peer_->last_received; } else { queue_state_.majority_replicated_op_id = new_majority_replicated_opid; } } peer->leader_lease_expiration.OnReplyFromFollower(); peer->leader_ht_lease_expiration.OnReplyFromFollower(); majority_replicated.op_id = queue_state_.majority_replicated_op_id; majority_replicated.leader_lease_expiration = LeaderLeaseExpirationWatermark(); majority_replicated.ht_lease_expiration = HybridTimeLeaseExpirationWatermark(); majority_replicated.num_sst_files = NumSSTFilesWatermark(); if (peer->last_received == queue_state_.last_applied_op_id) { majority_replicated.peer_got_all_ops = peer->uuid; } } UpdateAllReplicatedOpId(&queue_state_.all_replicated_op_id); UpdateAllAppliedOpId(&queue_state_.all_applied_op_id); auto evict_index = GetCDCConsumerOpIdToEvict().index; int32_t lagging_follower_threshold = FLAGS_consensus_lagging_follower_threshold; if (lagging_follower_threshold > 0) { UpdateAllNonLaggingReplicatedOpId(lagging_follower_threshold); evict_index = std::min(evict_index, queue_state_.all_nonlagging_replicated_op_id.index); } else { evict_index = std::min(evict_index, queue_state_.all_replicated_op_id.index); } log_cache_.EvictThroughOp(evict_index); UpdateMetrics(); } if (mode_copy == Mode::LEADER) { NotifyObserversOfMajorityReplOpChange(majority_replicated); } return result; } PeerMessageQueue::TrackedPeer PeerMessageQueue::GetTrackedPeerForTests(string uuid) { LockGuard scoped_lock(queue_lock_); TrackedPeer* tracked = FindOrDie(peers_map_, uuid); return *tracked; } OpId PeerMessageQueue::TEST_GetAllReplicatedIndex() const { LockGuard lock(queue_lock_); return queue_state_.all_replicated_op_id; } OpId PeerMessageQueue::GetAllAppliedOpId() const { LockGuard lock(queue_lock_); return queue_state_.all_applied_op_id; } OpId PeerMessageQueue::TEST_GetCommittedIndex() const { LockGuard lock(queue_lock_); return queue_state_.committed_op_id; } OpId PeerMessageQueue::TEST_GetMajorityReplicatedOpId() const { LockGuard lock(queue_lock_); return queue_state_.majority_replicated_op_id; } OpId PeerMessageQueue::TEST_GetLastAppended() const { LockGuard lock(queue_lock_); return queue_state_.last_appended; } OpId PeerMessageQueue::TEST_GetLastAppliedOpId() const { LockGuard lock(queue_lock_); return queue_state_.last_applied_op_id; } void PeerMessageQueue::UpdateMetrics() { // Since operations have consecutive indices we can update the metrics based on simple index math. metrics_.num_majority_done_ops->set_value( queue_state_.committed_op_id.index - queue_state_.all_replicated_op_id.index); metrics_.num_in_progress_ops->set_value( queue_state_.last_appended.index - queue_state_.committed_op_id.index); } void PeerMessageQueue::DumpToHtml(std::ostream& out) const { using std::endl; LockGuard lock(queue_lock_); out << "<h3>Watermarks</h3>" << endl; out << "<table>" << endl;; out << " <tr><th>Peer</th><th>Watermark</th></tr>" << endl; for (const PeersMap::value_type& entry : peers_map_) { out << Substitute(" <tr><td>$0</td><td>$1</td></tr>", EscapeForHtmlToString(entry.first), EscapeForHtmlToString(entry.second->ToString())) << endl; } out << "</table>" << endl; log_cache_.DumpToHtml(out); } void PeerMessageQueue::ClearUnlocked() { STLDeleteValues(&peers_map_); queue_state_.state = State::kQueueClosed; } void PeerMessageQueue::Close() { if (installed_num_sst_files_changed_listener_) { context_->ListenNumSSTFilesChanged(std::function<void()>()); installed_num_sst_files_changed_listener_ = false; } raft_pool_observers_token_->Shutdown(); LockGuard lock(queue_lock_); ClearUnlocked(); } string PeerMessageQueue::ToString() const { // Even though metrics are thread-safe obtain the lock so that we get a "consistent" snapshot of // the metrics. LockGuard lock(queue_lock_); return ToStringUnlocked(); } string PeerMessageQueue::ToStringUnlocked() const { return Substitute("Consensus queue metrics:" "Only Majority Done Ops: $0, In Progress Ops: $1, Cache: $2", metrics_.num_majority_done_ops->value(), metrics_.num_in_progress_ops->value(), log_cache_.StatsString()); } void PeerMessageQueue::RegisterObserver(PeerMessageQueueObserver* observer) { LockGuard lock(queue_lock_); auto iter = std::find(observers_.begin(), observers_.end(), observer); if (iter == observers_.end()) { observers_.push_back(observer); } } Status PeerMessageQueue::UnRegisterObserver(PeerMessageQueueObserver* observer) { LockGuard lock(queue_lock_); auto iter = std::find(observers_.begin(), observers_.end(), observer); if (iter == observers_.end()) { return STATUS(NotFound, "Can't find observer."); } observers_.erase(iter); return Status::OK(); } const char* PeerMessageQueue::ModeToStr(Mode mode) { switch (mode) { case Mode::LEADER: return "LEADER"; case Mode::NON_LEADER: return "NON_LEADER"; } FATAL_INVALID_ENUM_VALUE(PeerMessageQueue::Mode, mode); } const char* PeerMessageQueue::StateToStr(State state) { switch (state) { case State::kQueueConstructed: return "QUEUE_CONSTRUCTED"; case State::kQueueOpen: return "QUEUE_OPEN"; case State::kQueueClosed: return "QUEUE_CLOSED"; } FATAL_INVALID_ENUM_VALUE(PeerMessageQueue::State, state); } bool PeerMessageQueue::IsOpInLog(const yb::OpId& desired_op) const { auto result = log_cache_.LookupOpId(desired_op.index); if (PREDICT_TRUE(result.ok())) { return desired_op == *result; } if (PREDICT_TRUE(result.status().IsNotFound() || result.status().IsIncomplete())) { return false; } LOG_WITH_PREFIX_UNLOCKED(FATAL) << "Error while reading the log: " << result.status(); return false; // Unreachable; here to squelch GCC warning. } void PeerMessageQueue::NotifyObserversOfMajorityReplOpChange( const MajorityReplicatedData& majority_replicated_data) { WARN_NOT_OK(raft_pool_observers_token_->SubmitClosure( Bind(&PeerMessageQueue::NotifyObserversOfMajorityReplOpChangeTask, Unretained(this), majority_replicated_data)), LogPrefixUnlocked() + "Unable to notify RaftConsensus of " "majority replicated op change."); } template <class Func> void PeerMessageQueue::NotifyObservers(const char* title, Func&& func) { WARN_NOT_OK( raft_pool_observers_token_->SubmitFunc( [this, func = std::move(func)] { MAYBE_INJECT_RANDOM_LATENCY(FLAGS_consensus_inject_latency_ms_in_notifications); std::vector<PeerMessageQueueObserver*> copy; { LockGuard lock(queue_lock_); copy = observers_; } for (PeerMessageQueueObserver* observer : copy) { func(observer); } }), Format("$0Unable to notify observers for $1.", LogPrefixUnlocked(), title)); } void PeerMessageQueue::NotifyObserversOfTermChange(int64_t term) { NotifyObservers("term change", [term](PeerMessageQueueObserver* observer) { observer->NotifyTermChange(term); }); } void PeerMessageQueue::NotifyObserversOfMajorityReplOpChangeTask( const MajorityReplicatedData& majority_replicated_data) { std::vector<PeerMessageQueueObserver*> copy; { LockGuard lock(queue_lock_); copy = observers_; } // TODO move commit index advancement here so that the queue is not dependent on consensus at all, // but that requires a bit more work. OpId new_committed_op_id; OpId last_applied_op_id; for (PeerMessageQueueObserver* observer : copy) { observer->UpdateMajorityReplicated( majority_replicated_data, &new_committed_op_id, &last_applied_op_id); } { LockGuard lock(queue_lock_); if (!new_committed_op_id.empty() && new_committed_op_id.index > queue_state_.committed_op_id.index) { queue_state_.committed_op_id = new_committed_op_id; } queue_state_.last_applied_op_id.MakeAtLeast(last_applied_op_id); local_peer_->last_applied = queue_state_.last_applied_op_id; UpdateAllAppliedOpId(&queue_state_.all_applied_op_id); } } void PeerMessageQueue::NotifyObserversOfFailedFollower(const string& uuid, const string& reason) { int64_t current_term; { LockGuard lock(queue_lock_); current_term = queue_state_.current_term; } NotifyObserversOfFailedFollower(uuid, current_term, reason); } void PeerMessageQueue::NotifyObserversOfFailedFollower(const string& uuid, int64_t term, const string& reason) { NotifyObservers("failed follower", [uuid, term, reason](PeerMessageQueueObserver* observer) { observer->NotifyFailedFollower(uuid, term, reason); }); } bool PeerMessageQueue::PeerAcceptedOurLease(const std::string& uuid) const { std::lock_guard<simple_spinlock> lock(queue_lock_); TrackedPeer* peer = FindPtrOrNull(peers_map_, uuid); if (peer == nullptr) { return false; } return peer->leader_lease_expiration.last_received != CoarseTimePoint(); } bool PeerMessageQueue::CanPeerBecomeLeader(const std::string& peer_uuid) const { std::lock_guard<simple_spinlock> lock(queue_lock_); TrackedPeer* peer = FindPtrOrNull(peers_map_, peer_uuid); if (peer == nullptr) { LOG(ERROR) << "Invalid peer UUID: " << peer_uuid; return false; } const bool peer_can_be_leader = peer->last_received >= queue_state_.majority_replicated_op_id; if (!peer_can_be_leader) { LOG(INFO) << Format( "Peer $0 cannot become Leader as it is not caught up: Majority OpId $1, Peer OpId $2", peer_uuid, queue_state_.majority_replicated_op_id, peer->last_received); } return peer_can_be_leader; } OpId PeerMessageQueue::PeerLastReceivedOpId(const TabletServerId& uuid) const { std::lock_guard<simple_spinlock> lock(queue_lock_); TrackedPeer* peer = FindPtrOrNull(peers_map_, uuid); if (peer == nullptr) { LOG(ERROR) << "Invalid peer UUID: " << uuid; return OpId::Min(); } return peer->last_received; } string PeerMessageQueue::GetUpToDatePeer() const { OpId highest_op_id = OpId::Min(); std::vector<std::string> candidates; { std::lock_guard<simple_spinlock> lock(queue_lock_); for (const PeersMap::value_type& entry : peers_map_) { if (local_peer_uuid_ == entry.first) { continue; } if (highest_op_id > entry.second->last_received) { continue; } else if (highest_op_id == entry.second->last_received) { candidates.push_back(entry.first); } else { candidates = {entry.first}; highest_op_id = entry.second->last_received; } } } if (candidates.empty()) { return string(); } size_t index = 0; if (candidates.size() > 1) { // choose randomly among candidates at the same opid index = RandomUniformInt<size_t>(0, candidates.size() - 1); } return candidates[index]; } PeerMessageQueue::~PeerMessageQueue() { Close(); } string PeerMessageQueue::LogPrefixUnlocked() const { // TODO: we should probably use an atomic here. We'll just annotate away the TSAN error for now, // since the worst case is a slightly out-of-date log message, and not very likely. Mode mode = ANNOTATE_UNPROTECTED_READ(queue_state_.mode); return Substitute("T $0 P $1 [$2]: ", tablet_id_, local_peer_uuid_, ModeToStr(mode)); } string PeerMessageQueue::QueueState::ToString() const { return Format( "All replicated op: $0, Majority replicated op: $1, Committed index: $2, Last applied: $3, " "Last appended: $4, Current term: $5, Majority size: $6, State: $7, Mode: $8$9", /* 0 */ all_replicated_op_id, /* 1 */ majority_replicated_op_id, /* 2 */ committed_op_id, /* 3 */ last_applied_op_id, /* 4 */ last_appended, /* 5 */ current_term, /* 6 */ majority_size_, /* 7 */ StateToStr(state), /* 8 */ ModeToStr(mode), /* 9 */ active_config ? ", active raft config: " + active_config->ShortDebugString() : ""); } size_t PeerMessageQueue::LogCacheSize() { return log_cache_.BytesUsed(); } size_t PeerMessageQueue::EvictLogCache(size_t bytes_to_evict) { return log_cache_.EvictThroughOp(std::numeric_limits<int64_t>::max(), bytes_to_evict); } Status PeerMessageQueue::FlushLogIndex() { return log_cache_.FlushIndex(); } void PeerMessageQueue::TrackOperationsMemory(const OpIds& op_ids) { log_cache_.TrackOperationsMemory(op_ids); } Result<OpId> PeerMessageQueue::TEST_GetLastOpIdWithType( int64_t max_allowed_index, OperationType op_type) { return log_cache_.TEST_GetLastOpIdWithType(max_allowed_index, op_type); } Status ValidateFlags() { // Normally we would have used // DEFINE_validator(rpc_throttle_threshold_bytes, &RpcThrottleThresholdBytesValidator); // right after defining the rpc_throttle_threshold_bytes flag. However, this leads to a segfault // in the LTO-enabled build, presumably due to indeterminate order of static initialization. // Instead, we invoke this function from master/tserver main() functions when static // initialization is already finished. if (!RpcThrottleThresholdBytesValidator( "rpc_throttle_threshold_bytes", FLAGS_rpc_throttle_threshold_bytes)) { return STATUS(InvalidArgument, "Flag validation failed"); } return Status::OK(); } } // namespace consensus } // namespace yb
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %r9 push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0x876f, %rsi lea addresses_UC_ht+0x167, %rdi nop nop nop nop nop cmp $32597, %rdx mov $38, %rcx rep movsb nop nop nop nop xor %rbx, %rbx lea addresses_WT_ht+0x6d6f, %r9 nop cmp $58665, %r10 mov $0x6162636465666768, %rbx movq %rbx, %xmm5 vmovups %ymm5, (%r9) nop nop nop nop nop cmp $21388, %r10 lea addresses_WC_ht+0x1016f, %r10 sub $13267, %rcx mov $0x6162636465666768, %rdx movq %rdx, (%r10) nop nop nop nop and $30470, %r9 lea addresses_WT_ht+0xc56f, %rsi lea addresses_WC_ht+0x161ef, %rdi nop nop nop add $26628, %r14 mov $87, %rcx rep movsb nop nop nop nop nop add %r9, %r9 lea addresses_WT_ht+0x5b6f, %rsi lea addresses_D_ht+0x1689f, %rdi nop nop add $25316, %rbx mov $42, %rcx rep movsb nop nop nop nop nop and $39887, %rsi lea addresses_WC_ht+0xb2df, %rdi nop nop nop nop xor %r10, %r10 movb (%rdi), %r14b nop nop nop nop nop add %rdi, %rdi lea addresses_WT_ht+0x7b6f, %rcx nop nop nop nop xor $29704, %rsi mov $0x6162636465666768, %rbx movq %rbx, %xmm4 vmovups %ymm4, (%rcx) nop lfence lea addresses_A_ht+0x876f, %rcx clflush (%rcx) nop nop nop nop cmp %r9, %r9 mov $0x6162636465666768, %rdx movq %rdx, %xmm0 movups %xmm0, (%rcx) nop nop nop nop nop and %r10, %r10 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %r9 pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r14 push %r15 push %r8 push %r9 push %rdx // Store lea addresses_WT+0x11a87, %rdx clflush (%rdx) nop sub %r14, %r14 mov $0x5152535455565758, %r15 movq %r15, %xmm2 movups %xmm2, (%rdx) nop nop nop nop sub $12564, %r15 // Store mov $0x1b4ac20000000eef, %rdx nop nop inc %r13 mov $0x5152535455565758, %r8 movq %r8, (%rdx) xor $26421, %r14 // Store lea addresses_normal+0x1b18f, %r13 nop nop cmp %r11, %r11 mov $0x5152535455565758, %rdx movq %rdx, %xmm6 movups %xmm6, (%r13) nop nop nop nop add $49863, %r9 // Store lea addresses_normal+0x17362, %r8 nop nop nop and $10740, %rdx movw $0x5152, (%r8) nop xor %r9, %r9 // Store lea addresses_normal+0x1d647, %r15 nop nop nop nop nop sub %r11, %r11 movw $0x5152, (%r15) nop xor %r11, %r11 // Store lea addresses_UC+0x636f, %r8 dec %r13 movw $0x5152, (%r8) nop nop nop xor %r13, %r13 // Faulty Load lea addresses_US+0x1556f, %r14 nop nop nop nop sub $57396, %r13 movb (%r14), %r15b lea oracles, %r14 and $0xff, %r15 shlq $12, %r15 mov (%r14,%r15,1), %r15 pop %rdx pop %r9 pop %r8 pop %r15 pop %r14 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_US', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_WT', 'congruent': 3}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_NC', 'congruent': 6}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_normal', 'congruent': 3}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal', 'congruent': 0}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal', 'congruent': 3}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 2, 'type': 'addresses_UC', 'congruent': 8}, 'OP': 'STOR'} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_US', 'congruent': 0}} <gen_prepare_buffer> {'dst': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_WC_ht'}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_WT_ht', 'congruent': 10}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_WC_ht', 'congruent': 10}, 'OP': 'STOR'} {'dst': {'same': False, 'congruent': 7, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_WT_ht'}} {'dst': {'same': False, 'congruent': 4, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_WT_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_WC_ht', 'congruent': 1}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_WT_ht', 'congruent': 9}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_A_ht', 'congruent': 8}, 'OP': 'STOR'} {'00': 1} 00 */
; A292372: A binary encoding of 2-digits in base-4 representation of n. ; Submitted by Jon Maiga ; 0,0,1,0,0,0,1,0,2,2,3,2,0,0,1,0,0,0,1,0,0,0,1,0,2,2,3,2,0,0,1,0,4,4,5,4,4,4,5,4,6,6,7,6,4,4,5,4,0,0,1,0,0,0,1,0,2,2,3,2,0,0,1,0,0,0,1,0,0,0,1,0,2,2,3,2,0,0,1,0,0,0,1,0,0,0,1,0,2,2,3,2,0,0,1,0,4,4,5,4 mov $3,1 lpb $0 mov $2,$0 div $0,4 mod $2,4 cmp $2,2 mul $2,$3 add $1,$2 mul $3,2 lpe mov $0,$1
; A111597: Lah numbers: n!*binomial(n-1,6)/7!. ; Submitted by Christian Krause ; 1,56,2016,60480,1663200,43908480,1141620480,29682132480,779155977600,20777492736000,565147802419200,15721384321843200,448059453172531200,13097122477350912000,392913674320527360000,12101741169072242688000,382717564471909675008000,12427064446382008270848000,414235481546066942361600000,14171213842365448028160000000,497409605867027225788416000000,17906745811212980128382976000000,660921709032042721102135296000000,25000082037299007276472074240000000,968753178945336531963292876800000000 mov $1,$0 add $0,7 bin $0,$1 add $1,6 lpb $1 mul $0,$1 sub $1,1 lpe div $0,720
PowerPlant_Object: db $2e ; border block def_warps warp 4, 35, 3, LAST_MAP warp 5, 35, 3, LAST_MAP warp 0, 11, 3, LAST_MAP def_signs def_objects object SPRITE_POKE_BALL, 9, 20, STAY, NONE, 1, VOLTORB, 40 object SPRITE_POKE_BALL, 32, 18, STAY, NONE, 2, VOLTORB, 40 object SPRITE_POKE_BALL, 21, 25, STAY, NONE, 3, VOLTORB, 40 object SPRITE_POKE_BALL, 25, 18, STAY, NONE, 4, ELECTRODE, 43 object SPRITE_POKE_BALL, 23, 34, STAY, NONE, 5, VOLTORB, 40 object SPRITE_POKE_BALL, 26, 28, STAY, NONE, 6, VOLTORB, 40 object SPRITE_POKE_BALL, 21, 14, STAY, NONE, 7, ELECTRODE, 43 object SPRITE_POKE_BALL, 37, 32, STAY, NONE, 8, VOLTORB, 40 object SPRITE_BIRD, 4, 9, STAY, UP, 9, ZAPDOS, 50 object SPRITE_POKE_BALL, 7, 25, STAY, NONE, 10, CARBOS object SPRITE_POKE_BALL, 28, 3, STAY, NONE, 11, HP_UP object SPRITE_POKE_BALL, 34, 3, STAY, NONE, 12, RARE_CANDY object SPRITE_POKE_BALL, 26, 32, STAY, NONE, 13, TM_THUNDER object SPRITE_POKE_BALL, 20, 32, STAY, NONE, 14, TM_REFLECT def_warps_to POWER_PLANT
#include <iostream> #include <iomanip> #include <cstdint> #include "color/color.hpp" int main( int argc, char *argv[] ) { // Instead of float you may put std::uint8_t,std::uint16_t, std::uint32_t, std::uint64_t, double, long double color::cmyk<float> c; // initialize c before get. c = color::constant::turquoise_t{}; // Here is how to get white component. auto white = color::get::white( c ); // Now do whatever you wan to do std::cout << white << std::endl; return EXIT_SUCCESS; }
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/monitor/v20180724/MonitorClient.h> #include <tencentcloud/core/Executor.h> #include <tencentcloud/core/Runnable.h> using namespace TencentCloud; using namespace TencentCloud::Monitor::V20180724; using namespace TencentCloud::Monitor::V20180724::Model; using namespace std; namespace { const string VERSION = "2018-07-24"; const string ENDPOINT = "monitor.tencentcloudapi.com"; } MonitorClient::MonitorClient(const Credential &credential, const string &region) : MonitorClient(credential, region, ClientProfile()) { } MonitorClient::MonitorClient(const Credential &credential, const string &region, const ClientProfile &profile) : AbstractClient(ENDPOINT, VERSION, credential, region, profile) { } MonitorClient::BindingPolicyObjectOutcome MonitorClient::BindingPolicyObject(const BindingPolicyObjectRequest &request) { auto outcome = MakeRequest(request, "BindingPolicyObject"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); BindingPolicyObjectResponse rsp = BindingPolicyObjectResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return BindingPolicyObjectOutcome(rsp); else return BindingPolicyObjectOutcome(o.GetError()); } else { return BindingPolicyObjectOutcome(outcome.GetError()); } } void MonitorClient::BindingPolicyObjectAsync(const BindingPolicyObjectRequest& request, const BindingPolicyObjectAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->BindingPolicyObject(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::BindingPolicyObjectOutcomeCallable MonitorClient::BindingPolicyObjectCallable(const BindingPolicyObjectRequest &request) { auto task = std::make_shared<std::packaged_task<BindingPolicyObjectOutcome()>>( [this, request]() { return this->BindingPolicyObject(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::CreateAlarmNoticeOutcome MonitorClient::CreateAlarmNotice(const CreateAlarmNoticeRequest &request) { auto outcome = MakeRequest(request, "CreateAlarmNotice"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateAlarmNoticeResponse rsp = CreateAlarmNoticeResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateAlarmNoticeOutcome(rsp); else return CreateAlarmNoticeOutcome(o.GetError()); } else { return CreateAlarmNoticeOutcome(outcome.GetError()); } } void MonitorClient::CreateAlarmNoticeAsync(const CreateAlarmNoticeRequest& request, const CreateAlarmNoticeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateAlarmNotice(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::CreateAlarmNoticeOutcomeCallable MonitorClient::CreateAlarmNoticeCallable(const CreateAlarmNoticeRequest &request) { auto task = std::make_shared<std::packaged_task<CreateAlarmNoticeOutcome()>>( [this, request]() { return this->CreateAlarmNotice(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::CreateAlarmPolicyOutcome MonitorClient::CreateAlarmPolicy(const CreateAlarmPolicyRequest &request) { auto outcome = MakeRequest(request, "CreateAlarmPolicy"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateAlarmPolicyResponse rsp = CreateAlarmPolicyResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateAlarmPolicyOutcome(rsp); else return CreateAlarmPolicyOutcome(o.GetError()); } else { return CreateAlarmPolicyOutcome(outcome.GetError()); } } void MonitorClient::CreateAlarmPolicyAsync(const CreateAlarmPolicyRequest& request, const CreateAlarmPolicyAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateAlarmPolicy(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::CreateAlarmPolicyOutcomeCallable MonitorClient::CreateAlarmPolicyCallable(const CreateAlarmPolicyRequest &request) { auto task = std::make_shared<std::packaged_task<CreateAlarmPolicyOutcome()>>( [this, request]() { return this->CreateAlarmPolicy(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::CreatePolicyGroupOutcome MonitorClient::CreatePolicyGroup(const CreatePolicyGroupRequest &request) { auto outcome = MakeRequest(request, "CreatePolicyGroup"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreatePolicyGroupResponse rsp = CreatePolicyGroupResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreatePolicyGroupOutcome(rsp); else return CreatePolicyGroupOutcome(o.GetError()); } else { return CreatePolicyGroupOutcome(outcome.GetError()); } } void MonitorClient::CreatePolicyGroupAsync(const CreatePolicyGroupRequest& request, const CreatePolicyGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreatePolicyGroup(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::CreatePolicyGroupOutcomeCallable MonitorClient::CreatePolicyGroupCallable(const CreatePolicyGroupRequest &request) { auto task = std::make_shared<std::packaged_task<CreatePolicyGroupOutcome()>>( [this, request]() { return this->CreatePolicyGroup(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DeleteAlarmNoticesOutcome MonitorClient::DeleteAlarmNotices(const DeleteAlarmNoticesRequest &request) { auto outcome = MakeRequest(request, "DeleteAlarmNotices"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteAlarmNoticesResponse rsp = DeleteAlarmNoticesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteAlarmNoticesOutcome(rsp); else return DeleteAlarmNoticesOutcome(o.GetError()); } else { return DeleteAlarmNoticesOutcome(outcome.GetError()); } } void MonitorClient::DeleteAlarmNoticesAsync(const DeleteAlarmNoticesRequest& request, const DeleteAlarmNoticesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteAlarmNotices(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DeleteAlarmNoticesOutcomeCallable MonitorClient::DeleteAlarmNoticesCallable(const DeleteAlarmNoticesRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteAlarmNoticesOutcome()>>( [this, request]() { return this->DeleteAlarmNotices(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DeleteAlarmPolicyOutcome MonitorClient::DeleteAlarmPolicy(const DeleteAlarmPolicyRequest &request) { auto outcome = MakeRequest(request, "DeleteAlarmPolicy"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteAlarmPolicyResponse rsp = DeleteAlarmPolicyResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteAlarmPolicyOutcome(rsp); else return DeleteAlarmPolicyOutcome(o.GetError()); } else { return DeleteAlarmPolicyOutcome(outcome.GetError()); } } void MonitorClient::DeleteAlarmPolicyAsync(const DeleteAlarmPolicyRequest& request, const DeleteAlarmPolicyAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteAlarmPolicy(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DeleteAlarmPolicyOutcomeCallable MonitorClient::DeleteAlarmPolicyCallable(const DeleteAlarmPolicyRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteAlarmPolicyOutcome()>>( [this, request]() { return this->DeleteAlarmPolicy(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DeletePolicyGroupOutcome MonitorClient::DeletePolicyGroup(const DeletePolicyGroupRequest &request) { auto outcome = MakeRequest(request, "DeletePolicyGroup"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeletePolicyGroupResponse rsp = DeletePolicyGroupResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeletePolicyGroupOutcome(rsp); else return DeletePolicyGroupOutcome(o.GetError()); } else { return DeletePolicyGroupOutcome(outcome.GetError()); } } void MonitorClient::DeletePolicyGroupAsync(const DeletePolicyGroupRequest& request, const DeletePolicyGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeletePolicyGroup(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DeletePolicyGroupOutcomeCallable MonitorClient::DeletePolicyGroupCallable(const DeletePolicyGroupRequest &request) { auto task = std::make_shared<std::packaged_task<DeletePolicyGroupOutcome()>>( [this, request]() { return this->DeletePolicyGroup(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeAccidentEventListOutcome MonitorClient::DescribeAccidentEventList(const DescribeAccidentEventListRequest &request) { auto outcome = MakeRequest(request, "DescribeAccidentEventList"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeAccidentEventListResponse rsp = DescribeAccidentEventListResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeAccidentEventListOutcome(rsp); else return DescribeAccidentEventListOutcome(o.GetError()); } else { return DescribeAccidentEventListOutcome(outcome.GetError()); } } void MonitorClient::DescribeAccidentEventListAsync(const DescribeAccidentEventListRequest& request, const DescribeAccidentEventListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeAccidentEventList(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeAccidentEventListOutcomeCallable MonitorClient::DescribeAccidentEventListCallable(const DescribeAccidentEventListRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeAccidentEventListOutcome()>>( [this, request]() { return this->DescribeAccidentEventList(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeAlarmEventsOutcome MonitorClient::DescribeAlarmEvents(const DescribeAlarmEventsRequest &request) { auto outcome = MakeRequest(request, "DescribeAlarmEvents"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeAlarmEventsResponse rsp = DescribeAlarmEventsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeAlarmEventsOutcome(rsp); else return DescribeAlarmEventsOutcome(o.GetError()); } else { return DescribeAlarmEventsOutcome(outcome.GetError()); } } void MonitorClient::DescribeAlarmEventsAsync(const DescribeAlarmEventsRequest& request, const DescribeAlarmEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeAlarmEvents(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeAlarmEventsOutcomeCallable MonitorClient::DescribeAlarmEventsCallable(const DescribeAlarmEventsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeAlarmEventsOutcome()>>( [this, request]() { return this->DescribeAlarmEvents(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeAlarmHistoriesOutcome MonitorClient::DescribeAlarmHistories(const DescribeAlarmHistoriesRequest &request) { auto outcome = MakeRequest(request, "DescribeAlarmHistories"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeAlarmHistoriesResponse rsp = DescribeAlarmHistoriesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeAlarmHistoriesOutcome(rsp); else return DescribeAlarmHistoriesOutcome(o.GetError()); } else { return DescribeAlarmHistoriesOutcome(outcome.GetError()); } } void MonitorClient::DescribeAlarmHistoriesAsync(const DescribeAlarmHistoriesRequest& request, const DescribeAlarmHistoriesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeAlarmHistories(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeAlarmHistoriesOutcomeCallable MonitorClient::DescribeAlarmHistoriesCallable(const DescribeAlarmHistoriesRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeAlarmHistoriesOutcome()>>( [this, request]() { return this->DescribeAlarmHistories(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeAlarmMetricsOutcome MonitorClient::DescribeAlarmMetrics(const DescribeAlarmMetricsRequest &request) { auto outcome = MakeRequest(request, "DescribeAlarmMetrics"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeAlarmMetricsResponse rsp = DescribeAlarmMetricsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeAlarmMetricsOutcome(rsp); else return DescribeAlarmMetricsOutcome(o.GetError()); } else { return DescribeAlarmMetricsOutcome(outcome.GetError()); } } void MonitorClient::DescribeAlarmMetricsAsync(const DescribeAlarmMetricsRequest& request, const DescribeAlarmMetricsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeAlarmMetrics(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeAlarmMetricsOutcomeCallable MonitorClient::DescribeAlarmMetricsCallable(const DescribeAlarmMetricsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeAlarmMetricsOutcome()>>( [this, request]() { return this->DescribeAlarmMetrics(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeAlarmNoticeOutcome MonitorClient::DescribeAlarmNotice(const DescribeAlarmNoticeRequest &request) { auto outcome = MakeRequest(request, "DescribeAlarmNotice"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeAlarmNoticeResponse rsp = DescribeAlarmNoticeResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeAlarmNoticeOutcome(rsp); else return DescribeAlarmNoticeOutcome(o.GetError()); } else { return DescribeAlarmNoticeOutcome(outcome.GetError()); } } void MonitorClient::DescribeAlarmNoticeAsync(const DescribeAlarmNoticeRequest& request, const DescribeAlarmNoticeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeAlarmNotice(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeAlarmNoticeOutcomeCallable MonitorClient::DescribeAlarmNoticeCallable(const DescribeAlarmNoticeRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeAlarmNoticeOutcome()>>( [this, request]() { return this->DescribeAlarmNotice(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeAlarmNoticeCallbacksOutcome MonitorClient::DescribeAlarmNoticeCallbacks(const DescribeAlarmNoticeCallbacksRequest &request) { auto outcome = MakeRequest(request, "DescribeAlarmNoticeCallbacks"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeAlarmNoticeCallbacksResponse rsp = DescribeAlarmNoticeCallbacksResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeAlarmNoticeCallbacksOutcome(rsp); else return DescribeAlarmNoticeCallbacksOutcome(o.GetError()); } else { return DescribeAlarmNoticeCallbacksOutcome(outcome.GetError()); } } void MonitorClient::DescribeAlarmNoticeCallbacksAsync(const DescribeAlarmNoticeCallbacksRequest& request, const DescribeAlarmNoticeCallbacksAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeAlarmNoticeCallbacks(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeAlarmNoticeCallbacksOutcomeCallable MonitorClient::DescribeAlarmNoticeCallbacksCallable(const DescribeAlarmNoticeCallbacksRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeAlarmNoticeCallbacksOutcome()>>( [this, request]() { return this->DescribeAlarmNoticeCallbacks(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeAlarmNoticesOutcome MonitorClient::DescribeAlarmNotices(const DescribeAlarmNoticesRequest &request) { auto outcome = MakeRequest(request, "DescribeAlarmNotices"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeAlarmNoticesResponse rsp = DescribeAlarmNoticesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeAlarmNoticesOutcome(rsp); else return DescribeAlarmNoticesOutcome(o.GetError()); } else { return DescribeAlarmNoticesOutcome(outcome.GetError()); } } void MonitorClient::DescribeAlarmNoticesAsync(const DescribeAlarmNoticesRequest& request, const DescribeAlarmNoticesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeAlarmNotices(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeAlarmNoticesOutcomeCallable MonitorClient::DescribeAlarmNoticesCallable(const DescribeAlarmNoticesRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeAlarmNoticesOutcome()>>( [this, request]() { return this->DescribeAlarmNotices(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeAlarmPoliciesOutcome MonitorClient::DescribeAlarmPolicies(const DescribeAlarmPoliciesRequest &request) { auto outcome = MakeRequest(request, "DescribeAlarmPolicies"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeAlarmPoliciesResponse rsp = DescribeAlarmPoliciesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeAlarmPoliciesOutcome(rsp); else return DescribeAlarmPoliciesOutcome(o.GetError()); } else { return DescribeAlarmPoliciesOutcome(outcome.GetError()); } } void MonitorClient::DescribeAlarmPoliciesAsync(const DescribeAlarmPoliciesRequest& request, const DescribeAlarmPoliciesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeAlarmPolicies(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeAlarmPoliciesOutcomeCallable MonitorClient::DescribeAlarmPoliciesCallable(const DescribeAlarmPoliciesRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeAlarmPoliciesOutcome()>>( [this, request]() { return this->DescribeAlarmPolicies(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeAlarmPolicyOutcome MonitorClient::DescribeAlarmPolicy(const DescribeAlarmPolicyRequest &request) { auto outcome = MakeRequest(request, "DescribeAlarmPolicy"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeAlarmPolicyResponse rsp = DescribeAlarmPolicyResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeAlarmPolicyOutcome(rsp); else return DescribeAlarmPolicyOutcome(o.GetError()); } else { return DescribeAlarmPolicyOutcome(outcome.GetError()); } } void MonitorClient::DescribeAlarmPolicyAsync(const DescribeAlarmPolicyRequest& request, const DescribeAlarmPolicyAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeAlarmPolicy(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeAlarmPolicyOutcomeCallable MonitorClient::DescribeAlarmPolicyCallable(const DescribeAlarmPolicyRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeAlarmPolicyOutcome()>>( [this, request]() { return this->DescribeAlarmPolicy(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeAllNamespacesOutcome MonitorClient::DescribeAllNamespaces(const DescribeAllNamespacesRequest &request) { auto outcome = MakeRequest(request, "DescribeAllNamespaces"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeAllNamespacesResponse rsp = DescribeAllNamespacesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeAllNamespacesOutcome(rsp); else return DescribeAllNamespacesOutcome(o.GetError()); } else { return DescribeAllNamespacesOutcome(outcome.GetError()); } } void MonitorClient::DescribeAllNamespacesAsync(const DescribeAllNamespacesRequest& request, const DescribeAllNamespacesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeAllNamespaces(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeAllNamespacesOutcomeCallable MonitorClient::DescribeAllNamespacesCallable(const DescribeAllNamespacesRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeAllNamespacesOutcome()>>( [this, request]() { return this->DescribeAllNamespaces(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeBaseMetricsOutcome MonitorClient::DescribeBaseMetrics(const DescribeBaseMetricsRequest &request) { auto outcome = MakeRequest(request, "DescribeBaseMetrics"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeBaseMetricsResponse rsp = DescribeBaseMetricsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeBaseMetricsOutcome(rsp); else return DescribeBaseMetricsOutcome(o.GetError()); } else { return DescribeBaseMetricsOutcome(outcome.GetError()); } } void MonitorClient::DescribeBaseMetricsAsync(const DescribeBaseMetricsRequest& request, const DescribeBaseMetricsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeBaseMetrics(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeBaseMetricsOutcomeCallable MonitorClient::DescribeBaseMetricsCallable(const DescribeBaseMetricsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeBaseMetricsOutcome()>>( [this, request]() { return this->DescribeBaseMetrics(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeBasicAlarmListOutcome MonitorClient::DescribeBasicAlarmList(const DescribeBasicAlarmListRequest &request) { auto outcome = MakeRequest(request, "DescribeBasicAlarmList"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeBasicAlarmListResponse rsp = DescribeBasicAlarmListResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeBasicAlarmListOutcome(rsp); else return DescribeBasicAlarmListOutcome(o.GetError()); } else { return DescribeBasicAlarmListOutcome(outcome.GetError()); } } void MonitorClient::DescribeBasicAlarmListAsync(const DescribeBasicAlarmListRequest& request, const DescribeBasicAlarmListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeBasicAlarmList(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeBasicAlarmListOutcomeCallable MonitorClient::DescribeBasicAlarmListCallable(const DescribeBasicAlarmListRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeBasicAlarmListOutcome()>>( [this, request]() { return this->DescribeBasicAlarmList(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeBindingPolicyObjectListOutcome MonitorClient::DescribeBindingPolicyObjectList(const DescribeBindingPolicyObjectListRequest &request) { auto outcome = MakeRequest(request, "DescribeBindingPolicyObjectList"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeBindingPolicyObjectListResponse rsp = DescribeBindingPolicyObjectListResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeBindingPolicyObjectListOutcome(rsp); else return DescribeBindingPolicyObjectListOutcome(o.GetError()); } else { return DescribeBindingPolicyObjectListOutcome(outcome.GetError()); } } void MonitorClient::DescribeBindingPolicyObjectListAsync(const DescribeBindingPolicyObjectListRequest& request, const DescribeBindingPolicyObjectListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeBindingPolicyObjectList(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeBindingPolicyObjectListOutcomeCallable MonitorClient::DescribeBindingPolicyObjectListCallable(const DescribeBindingPolicyObjectListRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeBindingPolicyObjectListOutcome()>>( [this, request]() { return this->DescribeBindingPolicyObjectList(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeConditionsTemplateListOutcome MonitorClient::DescribeConditionsTemplateList(const DescribeConditionsTemplateListRequest &request) { auto outcome = MakeRequest(request, "DescribeConditionsTemplateList"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeConditionsTemplateListResponse rsp = DescribeConditionsTemplateListResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeConditionsTemplateListOutcome(rsp); else return DescribeConditionsTemplateListOutcome(o.GetError()); } else { return DescribeConditionsTemplateListOutcome(outcome.GetError()); } } void MonitorClient::DescribeConditionsTemplateListAsync(const DescribeConditionsTemplateListRequest& request, const DescribeConditionsTemplateListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeConditionsTemplateList(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeConditionsTemplateListOutcomeCallable MonitorClient::DescribeConditionsTemplateListCallable(const DescribeConditionsTemplateListRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeConditionsTemplateListOutcome()>>( [this, request]() { return this->DescribeConditionsTemplateList(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeMonitorTypesOutcome MonitorClient::DescribeMonitorTypes(const DescribeMonitorTypesRequest &request) { auto outcome = MakeRequest(request, "DescribeMonitorTypes"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeMonitorTypesResponse rsp = DescribeMonitorTypesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeMonitorTypesOutcome(rsp); else return DescribeMonitorTypesOutcome(o.GetError()); } else { return DescribeMonitorTypesOutcome(outcome.GetError()); } } void MonitorClient::DescribeMonitorTypesAsync(const DescribeMonitorTypesRequest& request, const DescribeMonitorTypesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeMonitorTypes(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeMonitorTypesOutcomeCallable MonitorClient::DescribeMonitorTypesCallable(const DescribeMonitorTypesRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeMonitorTypesOutcome()>>( [this, request]() { return this->DescribeMonitorTypes(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribePolicyConditionListOutcome MonitorClient::DescribePolicyConditionList(const DescribePolicyConditionListRequest &request) { auto outcome = MakeRequest(request, "DescribePolicyConditionList"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribePolicyConditionListResponse rsp = DescribePolicyConditionListResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribePolicyConditionListOutcome(rsp); else return DescribePolicyConditionListOutcome(o.GetError()); } else { return DescribePolicyConditionListOutcome(outcome.GetError()); } } void MonitorClient::DescribePolicyConditionListAsync(const DescribePolicyConditionListRequest& request, const DescribePolicyConditionListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribePolicyConditionList(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribePolicyConditionListOutcomeCallable MonitorClient::DescribePolicyConditionListCallable(const DescribePolicyConditionListRequest &request) { auto task = std::make_shared<std::packaged_task<DescribePolicyConditionListOutcome()>>( [this, request]() { return this->DescribePolicyConditionList(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribePolicyGroupInfoOutcome MonitorClient::DescribePolicyGroupInfo(const DescribePolicyGroupInfoRequest &request) { auto outcome = MakeRequest(request, "DescribePolicyGroupInfo"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribePolicyGroupInfoResponse rsp = DescribePolicyGroupInfoResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribePolicyGroupInfoOutcome(rsp); else return DescribePolicyGroupInfoOutcome(o.GetError()); } else { return DescribePolicyGroupInfoOutcome(outcome.GetError()); } } void MonitorClient::DescribePolicyGroupInfoAsync(const DescribePolicyGroupInfoRequest& request, const DescribePolicyGroupInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribePolicyGroupInfo(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribePolicyGroupInfoOutcomeCallable MonitorClient::DescribePolicyGroupInfoCallable(const DescribePolicyGroupInfoRequest &request) { auto task = std::make_shared<std::packaged_task<DescribePolicyGroupInfoOutcome()>>( [this, request]() { return this->DescribePolicyGroupInfo(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribePolicyGroupListOutcome MonitorClient::DescribePolicyGroupList(const DescribePolicyGroupListRequest &request) { auto outcome = MakeRequest(request, "DescribePolicyGroupList"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribePolicyGroupListResponse rsp = DescribePolicyGroupListResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribePolicyGroupListOutcome(rsp); else return DescribePolicyGroupListOutcome(o.GetError()); } else { return DescribePolicyGroupListOutcome(outcome.GetError()); } } void MonitorClient::DescribePolicyGroupListAsync(const DescribePolicyGroupListRequest& request, const DescribePolicyGroupListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribePolicyGroupList(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribePolicyGroupListOutcomeCallable MonitorClient::DescribePolicyGroupListCallable(const DescribePolicyGroupListRequest &request) { auto task = std::make_shared<std::packaged_task<DescribePolicyGroupListOutcome()>>( [this, request]() { return this->DescribePolicyGroupList(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeProductEventListOutcome MonitorClient::DescribeProductEventList(const DescribeProductEventListRequest &request) { auto outcome = MakeRequest(request, "DescribeProductEventList"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeProductEventListResponse rsp = DescribeProductEventListResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeProductEventListOutcome(rsp); else return DescribeProductEventListOutcome(o.GetError()); } else { return DescribeProductEventListOutcome(outcome.GetError()); } } void MonitorClient::DescribeProductEventListAsync(const DescribeProductEventListRequest& request, const DescribeProductEventListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeProductEventList(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeProductEventListOutcomeCallable MonitorClient::DescribeProductEventListCallable(const DescribeProductEventListRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeProductEventListOutcome()>>( [this, request]() { return this->DescribeProductEventList(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::DescribeStatisticDataOutcome MonitorClient::DescribeStatisticData(const DescribeStatisticDataRequest &request) { auto outcome = MakeRequest(request, "DescribeStatisticData"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeStatisticDataResponse rsp = DescribeStatisticDataResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeStatisticDataOutcome(rsp); else return DescribeStatisticDataOutcome(o.GetError()); } else { return DescribeStatisticDataOutcome(outcome.GetError()); } } void MonitorClient::DescribeStatisticDataAsync(const DescribeStatisticDataRequest& request, const DescribeStatisticDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeStatisticData(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::DescribeStatisticDataOutcomeCallable MonitorClient::DescribeStatisticDataCallable(const DescribeStatisticDataRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeStatisticDataOutcome()>>( [this, request]() { return this->DescribeStatisticData(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::GetMonitorDataOutcome MonitorClient::GetMonitorData(const GetMonitorDataRequest &request) { auto outcome = MakeRequest(request, "GetMonitorData"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); GetMonitorDataResponse rsp = GetMonitorDataResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return GetMonitorDataOutcome(rsp); else return GetMonitorDataOutcome(o.GetError()); } else { return GetMonitorDataOutcome(outcome.GetError()); } } void MonitorClient::GetMonitorDataAsync(const GetMonitorDataRequest& request, const GetMonitorDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->GetMonitorData(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::GetMonitorDataOutcomeCallable MonitorClient::GetMonitorDataCallable(const GetMonitorDataRequest &request) { auto task = std::make_shared<std::packaged_task<GetMonitorDataOutcome()>>( [this, request]() { return this->GetMonitorData(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::ModifyAlarmNoticeOutcome MonitorClient::ModifyAlarmNotice(const ModifyAlarmNoticeRequest &request) { auto outcome = MakeRequest(request, "ModifyAlarmNotice"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyAlarmNoticeResponse rsp = ModifyAlarmNoticeResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyAlarmNoticeOutcome(rsp); else return ModifyAlarmNoticeOutcome(o.GetError()); } else { return ModifyAlarmNoticeOutcome(outcome.GetError()); } } void MonitorClient::ModifyAlarmNoticeAsync(const ModifyAlarmNoticeRequest& request, const ModifyAlarmNoticeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyAlarmNotice(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::ModifyAlarmNoticeOutcomeCallable MonitorClient::ModifyAlarmNoticeCallable(const ModifyAlarmNoticeRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyAlarmNoticeOutcome()>>( [this, request]() { return this->ModifyAlarmNotice(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::ModifyAlarmPolicyConditionOutcome MonitorClient::ModifyAlarmPolicyCondition(const ModifyAlarmPolicyConditionRequest &request) { auto outcome = MakeRequest(request, "ModifyAlarmPolicyCondition"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyAlarmPolicyConditionResponse rsp = ModifyAlarmPolicyConditionResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyAlarmPolicyConditionOutcome(rsp); else return ModifyAlarmPolicyConditionOutcome(o.GetError()); } else { return ModifyAlarmPolicyConditionOutcome(outcome.GetError()); } } void MonitorClient::ModifyAlarmPolicyConditionAsync(const ModifyAlarmPolicyConditionRequest& request, const ModifyAlarmPolicyConditionAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyAlarmPolicyCondition(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::ModifyAlarmPolicyConditionOutcomeCallable MonitorClient::ModifyAlarmPolicyConditionCallable(const ModifyAlarmPolicyConditionRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyAlarmPolicyConditionOutcome()>>( [this, request]() { return this->ModifyAlarmPolicyCondition(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::ModifyAlarmPolicyInfoOutcome MonitorClient::ModifyAlarmPolicyInfo(const ModifyAlarmPolicyInfoRequest &request) { auto outcome = MakeRequest(request, "ModifyAlarmPolicyInfo"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyAlarmPolicyInfoResponse rsp = ModifyAlarmPolicyInfoResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyAlarmPolicyInfoOutcome(rsp); else return ModifyAlarmPolicyInfoOutcome(o.GetError()); } else { return ModifyAlarmPolicyInfoOutcome(outcome.GetError()); } } void MonitorClient::ModifyAlarmPolicyInfoAsync(const ModifyAlarmPolicyInfoRequest& request, const ModifyAlarmPolicyInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyAlarmPolicyInfo(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::ModifyAlarmPolicyInfoOutcomeCallable MonitorClient::ModifyAlarmPolicyInfoCallable(const ModifyAlarmPolicyInfoRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyAlarmPolicyInfoOutcome()>>( [this, request]() { return this->ModifyAlarmPolicyInfo(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::ModifyAlarmPolicyNoticeOutcome MonitorClient::ModifyAlarmPolicyNotice(const ModifyAlarmPolicyNoticeRequest &request) { auto outcome = MakeRequest(request, "ModifyAlarmPolicyNotice"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyAlarmPolicyNoticeResponse rsp = ModifyAlarmPolicyNoticeResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyAlarmPolicyNoticeOutcome(rsp); else return ModifyAlarmPolicyNoticeOutcome(o.GetError()); } else { return ModifyAlarmPolicyNoticeOutcome(outcome.GetError()); } } void MonitorClient::ModifyAlarmPolicyNoticeAsync(const ModifyAlarmPolicyNoticeRequest& request, const ModifyAlarmPolicyNoticeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyAlarmPolicyNotice(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::ModifyAlarmPolicyNoticeOutcomeCallable MonitorClient::ModifyAlarmPolicyNoticeCallable(const ModifyAlarmPolicyNoticeRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyAlarmPolicyNoticeOutcome()>>( [this, request]() { return this->ModifyAlarmPolicyNotice(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::ModifyAlarmPolicyStatusOutcome MonitorClient::ModifyAlarmPolicyStatus(const ModifyAlarmPolicyStatusRequest &request) { auto outcome = MakeRequest(request, "ModifyAlarmPolicyStatus"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyAlarmPolicyStatusResponse rsp = ModifyAlarmPolicyStatusResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyAlarmPolicyStatusOutcome(rsp); else return ModifyAlarmPolicyStatusOutcome(o.GetError()); } else { return ModifyAlarmPolicyStatusOutcome(outcome.GetError()); } } void MonitorClient::ModifyAlarmPolicyStatusAsync(const ModifyAlarmPolicyStatusRequest& request, const ModifyAlarmPolicyStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyAlarmPolicyStatus(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::ModifyAlarmPolicyStatusOutcomeCallable MonitorClient::ModifyAlarmPolicyStatusCallable(const ModifyAlarmPolicyStatusRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyAlarmPolicyStatusOutcome()>>( [this, request]() { return this->ModifyAlarmPolicyStatus(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::ModifyAlarmPolicyTasksOutcome MonitorClient::ModifyAlarmPolicyTasks(const ModifyAlarmPolicyTasksRequest &request) { auto outcome = MakeRequest(request, "ModifyAlarmPolicyTasks"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyAlarmPolicyTasksResponse rsp = ModifyAlarmPolicyTasksResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyAlarmPolicyTasksOutcome(rsp); else return ModifyAlarmPolicyTasksOutcome(o.GetError()); } else { return ModifyAlarmPolicyTasksOutcome(outcome.GetError()); } } void MonitorClient::ModifyAlarmPolicyTasksAsync(const ModifyAlarmPolicyTasksRequest& request, const ModifyAlarmPolicyTasksAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyAlarmPolicyTasks(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::ModifyAlarmPolicyTasksOutcomeCallable MonitorClient::ModifyAlarmPolicyTasksCallable(const ModifyAlarmPolicyTasksRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyAlarmPolicyTasksOutcome()>>( [this, request]() { return this->ModifyAlarmPolicyTasks(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::ModifyAlarmReceiversOutcome MonitorClient::ModifyAlarmReceivers(const ModifyAlarmReceiversRequest &request) { auto outcome = MakeRequest(request, "ModifyAlarmReceivers"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyAlarmReceiversResponse rsp = ModifyAlarmReceiversResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyAlarmReceiversOutcome(rsp); else return ModifyAlarmReceiversOutcome(o.GetError()); } else { return ModifyAlarmReceiversOutcome(outcome.GetError()); } } void MonitorClient::ModifyAlarmReceiversAsync(const ModifyAlarmReceiversRequest& request, const ModifyAlarmReceiversAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyAlarmReceivers(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::ModifyAlarmReceiversOutcomeCallable MonitorClient::ModifyAlarmReceiversCallable(const ModifyAlarmReceiversRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyAlarmReceiversOutcome()>>( [this, request]() { return this->ModifyAlarmReceivers(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::ModifyPolicyGroupOutcome MonitorClient::ModifyPolicyGroup(const ModifyPolicyGroupRequest &request) { auto outcome = MakeRequest(request, "ModifyPolicyGroup"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyPolicyGroupResponse rsp = ModifyPolicyGroupResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyPolicyGroupOutcome(rsp); else return ModifyPolicyGroupOutcome(o.GetError()); } else { return ModifyPolicyGroupOutcome(outcome.GetError()); } } void MonitorClient::ModifyPolicyGroupAsync(const ModifyPolicyGroupRequest& request, const ModifyPolicyGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyPolicyGroup(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::ModifyPolicyGroupOutcomeCallable MonitorClient::ModifyPolicyGroupCallable(const ModifyPolicyGroupRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyPolicyGroupOutcome()>>( [this, request]() { return this->ModifyPolicyGroup(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::PutMonitorDataOutcome MonitorClient::PutMonitorData(const PutMonitorDataRequest &request) { auto outcome = MakeRequest(request, "PutMonitorData"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); PutMonitorDataResponse rsp = PutMonitorDataResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return PutMonitorDataOutcome(rsp); else return PutMonitorDataOutcome(o.GetError()); } else { return PutMonitorDataOutcome(outcome.GetError()); } } void MonitorClient::PutMonitorDataAsync(const PutMonitorDataRequest& request, const PutMonitorDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->PutMonitorData(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::PutMonitorDataOutcomeCallable MonitorClient::PutMonitorDataCallable(const PutMonitorDataRequest &request) { auto task = std::make_shared<std::packaged_task<PutMonitorDataOutcome()>>( [this, request]() { return this->PutMonitorData(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::SendCustomAlarmMsgOutcome MonitorClient::SendCustomAlarmMsg(const SendCustomAlarmMsgRequest &request) { auto outcome = MakeRequest(request, "SendCustomAlarmMsg"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); SendCustomAlarmMsgResponse rsp = SendCustomAlarmMsgResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return SendCustomAlarmMsgOutcome(rsp); else return SendCustomAlarmMsgOutcome(o.GetError()); } else { return SendCustomAlarmMsgOutcome(outcome.GetError()); } } void MonitorClient::SendCustomAlarmMsgAsync(const SendCustomAlarmMsgRequest& request, const SendCustomAlarmMsgAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->SendCustomAlarmMsg(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::SendCustomAlarmMsgOutcomeCallable MonitorClient::SendCustomAlarmMsgCallable(const SendCustomAlarmMsgRequest &request) { auto task = std::make_shared<std::packaged_task<SendCustomAlarmMsgOutcome()>>( [this, request]() { return this->SendCustomAlarmMsg(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::SetDefaultAlarmPolicyOutcome MonitorClient::SetDefaultAlarmPolicy(const SetDefaultAlarmPolicyRequest &request) { auto outcome = MakeRequest(request, "SetDefaultAlarmPolicy"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); SetDefaultAlarmPolicyResponse rsp = SetDefaultAlarmPolicyResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return SetDefaultAlarmPolicyOutcome(rsp); else return SetDefaultAlarmPolicyOutcome(o.GetError()); } else { return SetDefaultAlarmPolicyOutcome(outcome.GetError()); } } void MonitorClient::SetDefaultAlarmPolicyAsync(const SetDefaultAlarmPolicyRequest& request, const SetDefaultAlarmPolicyAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->SetDefaultAlarmPolicy(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::SetDefaultAlarmPolicyOutcomeCallable MonitorClient::SetDefaultAlarmPolicyCallable(const SetDefaultAlarmPolicyRequest &request) { auto task = std::make_shared<std::packaged_task<SetDefaultAlarmPolicyOutcome()>>( [this, request]() { return this->SetDefaultAlarmPolicy(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::UnBindingAllPolicyObjectOutcome MonitorClient::UnBindingAllPolicyObject(const UnBindingAllPolicyObjectRequest &request) { auto outcome = MakeRequest(request, "UnBindingAllPolicyObject"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UnBindingAllPolicyObjectResponse rsp = UnBindingAllPolicyObjectResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UnBindingAllPolicyObjectOutcome(rsp); else return UnBindingAllPolicyObjectOutcome(o.GetError()); } else { return UnBindingAllPolicyObjectOutcome(outcome.GetError()); } } void MonitorClient::UnBindingAllPolicyObjectAsync(const UnBindingAllPolicyObjectRequest& request, const UnBindingAllPolicyObjectAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UnBindingAllPolicyObject(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::UnBindingAllPolicyObjectOutcomeCallable MonitorClient::UnBindingAllPolicyObjectCallable(const UnBindingAllPolicyObjectRequest &request) { auto task = std::make_shared<std::packaged_task<UnBindingAllPolicyObjectOutcome()>>( [this, request]() { return this->UnBindingAllPolicyObject(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } MonitorClient::UnBindingPolicyObjectOutcome MonitorClient::UnBindingPolicyObject(const UnBindingPolicyObjectRequest &request) { auto outcome = MakeRequest(request, "UnBindingPolicyObject"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UnBindingPolicyObjectResponse rsp = UnBindingPolicyObjectResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UnBindingPolicyObjectOutcome(rsp); else return UnBindingPolicyObjectOutcome(o.GetError()); } else { return UnBindingPolicyObjectOutcome(outcome.GetError()); } } void MonitorClient::UnBindingPolicyObjectAsync(const UnBindingPolicyObjectRequest& request, const UnBindingPolicyObjectAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UnBindingPolicyObject(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } MonitorClient::UnBindingPolicyObjectOutcomeCallable MonitorClient::UnBindingPolicyObjectCallable(const UnBindingPolicyObjectRequest &request) { auto task = std::make_shared<std::packaged_task<UnBindingPolicyObjectOutcome()>>( [this, request]() { return this->UnBindingPolicyObject(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); }
; A330569: a(n) = 1 if n is odd, otherwise a(n) = 2^(v-1)+1 where v is the 2-adic valuation of n (A007814(n)). ; 1,2,1,3,1,2,1,5,1,2,1,3,1,2,1,9,1,2,1,3,1,2,1,5,1,2,1,3,1,2,1,17,1,2,1,3,1,2,1,5,1,2,1,3,1,2,1,9,1,2,1,3,1,2,1,5,1,2,1,3,1,2,1,33,1,2,1,3,1,2,1,5,1,2,1,3,1,2,1,9,1,2,1,3,1 add $0,1 gcd $0,281474976710656 mov $1,$0 div $1,2 add $1,1
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <merkleblock.h> #include <hash.h> #include <consensus/consensus.h> #include "vbk/service_locator.hpp" #include "vbk/config.hpp" CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter* filter, const std::set<uint256>* txids) { header = block.GetBlockHeader(); std::vector<bool> vMatch; std::vector<uint256> vHashes; vMatch.reserve(block.vtx.size()); vHashes.reserve(block.vtx.size()); for (unsigned int i = 0; i < block.vtx.size(); i++) { const uint256& hash = block.vtx[i]->GetHash(); if (txids && txids->count(hash)) { vMatch.push_back(true); } else if (filter && filter->IsRelevantAndUpdate(*block.vtx[i])) { vMatch.push_back(true); vMatchedTxn.emplace_back(i, hash); } else { vMatch.push_back(false); } vHashes.push_back(hash); } txn = CPartialMerkleTree(vHashes, vMatch); } uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) { //we can never have zero txs in a merkle block, we always need the coinbase tx //if we do not have this assert, we can hit a memory access violation when indexing into vTxid assert(vTxid.size() != 0); if (height == 0) { // hash at height 0 is the txids themself return vTxid[pos]; } else { // calculate left hash uint256 left = CalcHash(height-1, pos*2, vTxid), right; // calculate right hash if not beyond the end of the array - copy left hash otherwise if (pos*2+1 < CalcTreeWidth(height-1)) right = CalcHash(height-1, pos*2+1, vTxid); else right = left; // combine subhashes return Hash(left.begin(), left.end(), right.begin(), right.end()); } } void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) { // determine whether this node is the parent of at least one matched txid bool fParentOfMatch = false; for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++) fParentOfMatch |= vMatch[p]; // store as flag bit vBits.push_back(fParentOfMatch); if (height==0 || !fParentOfMatch) { // if at height 0, or nothing interesting below, store hash and stop vHash.push_back(CalcHash(height, pos, vTxid)); } else { // otherwise, don't store any hash, but descend into the subtrees TraverseAndBuild(height-1, pos*2, vTxid, vMatch); if (pos*2+1 < CalcTreeWidth(height-1)) TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch); } } uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) { if (nBitsUsed >= vBits.size()) { // overflowed the bits array - failure fBad = true; return uint256(); } bool fParentOfMatch = vBits[nBitsUsed++]; if (height==0 || !fParentOfMatch) { // if at height 0, or nothing interesting below, use stored hash and do not descend if (nHashUsed >= vHash.size()) { // overflowed the hash array - failure fBad = true; return uint256(); } const uint256 &hash = vHash[nHashUsed++]; if (height==0 && fParentOfMatch) { // in case of height 0, we have a matched txid vMatch.push_back(hash); vnIndex.push_back(pos); } return hash; } else { // otherwise, descend into the subtrees to extract matched txids and hashes uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch, vnIndex), right; if (pos*2+1 < CalcTreeWidth(height-1)) { right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch, vnIndex); if (right == left) { // The left and right branches should never be identical, as the transaction // hashes covered by them must each be unique. fBad = true; } } else { right = left; } // and combine them before returning return Hash(left.begin(), left.end(), right.begin(), right.end()); } } CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) { // reset state vBits.clear(); vHash.clear(); // calculate height of tree int nHeight = 0; while (CalcTreeWidth(nHeight) > 1) nHeight++; // traverse the partial tree TraverseAndBuild(nHeight, 0, vTxid, vMatch); } CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {} uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) { vMatch.clear(); // An empty set will not work if (nTransactions == 0) return uint256(); // check for excessively high numbers of transactions auto& config = VeriBlock::getService<VeriBlock::Config>(); if (nTransactions > MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT + config.max_pop_tx_amount) return uint256(); // there can never be more hashes provided than one for every txid if (vHash.size() > nTransactions) return uint256(); // there must be at least one bit per node in the partial tree, and at least one node per hash if (vBits.size() < vHash.size()) return uint256(); // calculate height of tree int nHeight = 0; while (CalcTreeWidth(nHeight) > 1) nHeight++; // traverse the partial tree unsigned int nBitsUsed = 0, nHashUsed = 0; uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch, vnIndex); // verify that no problems occurred during the tree traversal if (fBad) return uint256(); // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence) if ((nBitsUsed+7)/8 != (vBits.size()+7)/8) return uint256(); // verify that all hashes were consumed if (nHashUsed != vHash.size()) return uint256(); return hashMerkleRoot; }
///* // * Copyright (c) 2021 George Beckstein // * SPDX-License-Identifier: Apache-2.0 // * // * Licensed under the Apache License, Version 2.0 (the "License"); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License // */ // //#include "MarqMenuCategory.hpp" // //void MarqMenuCategory::navigate_left() { // _idx--; // if(_idx < 0) { // _idx = _len; // } //} // //void MarqMenuCategory::navigate_right() { // _idx++; // if(_idx >= _len) { // _idx = 0; // } //} // //
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r13 push %r8 push %r9 push %rcx push %rdi push %rsi lea addresses_UC_ht+0x12697, %r9 nop nop nop nop nop inc %rcx mov $0x6162636465666768, %r11 movq %r11, %xmm0 and $0xffffffffffffffc0, %r9 vmovaps %ymm0, (%r9) nop nop nop nop xor $57054, %r8 lea addresses_WC_ht+0xf97, %rsi lea addresses_D_ht+0x1697, %rdi nop dec %r13 mov $71, %rcx rep movsq nop xor %rdi, %rdi lea addresses_D_ht+0x1097, %rsi nop nop nop sub %rdi, %rdi movl $0x61626364, (%rsi) nop dec %r11 lea addresses_WC_ht+0x17c97, %rcx add $16720, %rdi movw $0x6162, (%rcx) nop nop nop nop cmp %r13, %r13 lea addresses_WT_ht+0x4079, %rsi lea addresses_WC_ht+0x1cd17, %rdi nop nop nop nop nop sub $54678, %r13 mov $37, %rcx rep movsl nop nop inc %r9 lea addresses_WC_ht+0xd697, %r13 nop nop nop nop nop lfence movb $0x61, (%r13) add %rcx, %rcx lea addresses_WT_ht+0x1a897, %rsi lea addresses_WC_ht+0xa697, %rdi nop nop nop cmp $38871, %r12 mov $65, %rcx rep movsq and $61623, %r8 lea addresses_WT_ht+0x12c97, %r13 nop and $44256, %rcx movl $0x61626364, (%r13) nop nop cmp $20420, %r12 lea addresses_A_ht+0xaa4b, %rdi clflush (%rdi) nop nop nop and %rsi, %rsi mov (%rdi), %r13w nop nop nop nop cmp %rcx, %rcx lea addresses_WT_ht+0x6697, %r11 nop nop nop nop nop sub %r9, %r9 mov (%r11), %si nop nop nop nop add %r11, %r11 lea addresses_WC_ht+0x10037, %rsi nop nop inc %r8 movups (%rsi), %xmm6 vpextrq $0, %xmm6, %r12 nop nop add %rcx, %rcx lea addresses_normal_ht+0x8053, %rsi nop nop xor %rdi, %rdi mov (%rsi), %r8w nop nop nop sub $52145, %r12 pop %rsi pop %rdi pop %rcx pop %r9 pop %r8 pop %r13 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r13 push %r15 push %rdi push %rdx // Store lea addresses_UC+0x14ac6, %rdi nop nop sub $64908, %r13 movw $0x5152, (%rdi) nop nop nop nop nop sub $33985, %rdx // Store lea addresses_WT+0x1a697, %r12 nop nop sub $24977, %r11 mov $0x5152535455565758, %rdi movq %rdi, (%r12) nop sub %rdx, %rdx // Store lea addresses_normal+0x5697, %r15 nop nop nop nop nop inc %r11 movw $0x5152, (%r15) // Exception!!! mov (0), %rdi nop sub $56279, %rdx // Store lea addresses_normal+0x14797, %r10 inc %r11 movw $0x5152, (%r10) nop nop nop nop nop sub %r11, %r11 // Faulty Load lea addresses_WT+0x1a697, %rdx nop nop nop dec %r13 mov (%rdx), %r10d lea oracles, %rdi and $0xff, %r10 shlq $12, %r10 mov (%rdi,%r10,1), %r10 pop %rdx pop %rdi pop %r15 pop %r13 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 10, 'size': 2, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 8, 'size': 2, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': True, 'congruent': 5, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 9, 'size': 4, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 7, 'size': 2, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 11, 'size': 1, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 7, 'size': 4, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 2, 'size': 2, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': True, 'congruent': 4, 'size': 2, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 4, 'size': 16, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 2, 'size': 2, 'same': False, 'NT': False}} {'52': 21829} 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 */
; A001850: Central Delannoy numbers: a(n) = Sum_{k=0..n} C(n,k)*C(n+k,k). ; Submitted by Simon Strandgaard ; 1,3,13,63,321,1683,8989,48639,265729,1462563,8097453,45046719,251595969,1409933619,7923848253,44642381823,252055236609,1425834724419,8079317057869,45849429914943,260543813797441,1482376214227923,8443414161166173,48141245001931263,274738209148561921,1569245074591690083,8970232353223635949,51313576749006450879,293733710358893793729,1682471873186160624243,9642641465118083682429,55294491352291112747007,317241780630136241094657,1820991621200098527441027,10457362855894862001750669 mov $2,$0 lpb $0 mov $3,$2 bin $3,$0 sub $0,1 pow $3,2 add $1,$3 mul $1,2 lpe mov $0,$1 add $0,1
j Main j Interrupt j Exception Main: jal start start: li $t0,0x7fffffff and $ra,$ra,$t0 addi $ra,$ra,28 li $s0,0x40000000 jr $ra #set timer sw $zero,8($s0) #setTCON li $t0,0xfffe7960 sw $t0,0($s0) #setTH sw $t0,4($s0) #setTL #load data li $a0,0x00000000 li $t0,266 sw $t0,0($a0) li $t0,834 sw $t0,4($a0) li $t0,424 sw $t0,8($a0) li $t0,267 sw $t0,12($a0) li $t0,364 sw $t0,16($a0) li $t0,158 sw $t0,20($a0) li $t0,383 sw $t0,24($a0) li $t0,405 sw $t0,28($a0) li $t0,617 sw $t0,32($a0) li $t0,470 sw $t0,36($a0) li $t0,997 sw $t0,40($a0) li $t0,493 sw $t0,44($a0) li $t0,493 sw $t0,48($a0) li $t0,491 sw $t0,52($a0) li $t0,893 sw $t0,56($a0) li $t0,310 sw $t0,60($a0) li $t0,35 sw $t0,64($a0) li $t0,804 sw $t0,68($a0) li $t0,149 sw $t0,72($a0) li $t0,202 sw $t0,76($a0) li $t0,865 sw $t0,80($a0) li $t0,989 sw $t0,84($a0) li $t0,186 sw $t0,88($a0) li $t0,334 sw $t0,92($a0) li $t0,759 sw $t0,96($a0) li $t0,507 sw $t0,100($a0) li $t0,50 sw $t0,104($a0) li $t0,719 sw $t0,108($a0) li $t0,166 sw $t0,112($a0) li $t0,761 sw $t0,116($a0) li $t0,233 sw $t0,120($a0) li $t0,983 sw $t0,124($a0) li $t0,445 sw $t0,128($a0) li $t0,7 sw $t0,132($a0) li $t0,97 sw $t0,136($a0) li $t0,5 sw $t0,140($a0) li $t0,682 sw $t0,144($a0) li $t0,861 sw $t0,148($a0) li $t0,358 sw $t0,152($a0) li $t0,735 sw $t0,156($a0) li $t0,822 sw $t0,160($a0) li $t0,542 sw $t0,164($a0) li $t0,455 sw $t0,168($a0) li $t0,914 sw $t0,172($a0) li $t0,285 sw $t0,176($a0) li $t0,976 sw $t0,180($a0) li $t0,88 sw $t0,184($a0) li $t0,795 sw $t0,188($a0) li $t0,101 sw $t0,192($a0) li $t0,943 sw $t0,196($a0) li $t0,433 sw $t0,200($a0) li $t0,944 sw $t0,204($a0) li $t0,265 sw $t0,208($a0) li $t0,466 sw $t0,212($a0) li $t0,231 sw $t0,216($a0) li $t0,984 sw $t0,220($a0) li $t0,877 sw $t0,224($a0) li $t0,776 sw $t0,228($a0) li $t0,535 sw $t0,232($a0) li $t0,870 sw $t0,236($a0) li $t0,691 sw $t0,240($a0) li $t0,3 sw $t0,244($a0) li $t0,384 sw $t0,248($a0) li $t0,360 sw $t0,252($a0) li $t0,342 sw $t0,256($a0) li $t0,243 sw $t0,260($a0) li $t0,473 sw $t0,264($a0) li $t0,710 sw $t0,268($a0) li $t0,62 sw $t0,272($a0) li $t0,546 sw $t0,276($a0) li $t0,466 sw $t0,280($a0) li $t0,816 sw $t0,284($a0) li $t0,750 sw $t0,288($a0) li $t0,70 sw $t0,292($a0) li $t0,609 sw $t0,296($a0) li $t0,579 sw $t0,300($a0) li $t0,437 sw $t0,304($a0) li $t0,369 sw $t0,308($a0) li $t0,317 sw $t0,312($a0) li $t0,424 sw $t0,316($a0) li $t0,760 sw $t0,320($a0) li $t0,831 sw $t0,324($a0) li $t0,811 sw $t0,328($a0) li $t0,849 sw $t0,332($a0) li $t0,55 sw $t0,336($a0) li $t0,261 sw $t0,340($a0) li $t0,570 sw $t0,344($a0) li $t0,829 sw $t0,348($a0) li $t0,781 sw $t0,352($a0) li $t0,842 sw $t0,356($a0) li $t0,696 sw $t0,360($a0) li $t0,442 sw $t0,364($a0) li $t0,552 sw $t0,368($a0) li $t0,710 sw $t0,372($a0) li $t0,197 sw $t0,376($a0) li $t0,241 sw $t0,380($a0) li $t0,846 sw $t0,384($a0) li $t0,787 sw $t0,388($a0) li $t0,955 sw $t0,392($a0) li $t0,246 sw $t0,396($a0) li $t0,615 sw $t0,400($a0) li $t0,131 sw $t0,404($a0) li $t0,424 sw $t0,408($a0) li $t0,28 sw $t0,412($a0) li $t0,78 sw $t0,416($a0) li $t0,357 sw $t0,420($a0) li $t0,25 sw $t0,424($a0) li $t0,228 sw $t0,428($a0) li $t0,108 sw $t0,432($a0) li $t0,910 sw $t0,436($a0) li $t0,905 sw $t0,440($a0) li $t0,287 sw $t0,444($a0) li $t0,735 sw $t0,448($a0) li $t0,832 sw $t0,452($a0) li $t0,788 sw $t0,456($a0) li $t0,388 sw $t0,460($a0) li $t0,604 sw $t0,464($a0) li $t0,981 sw $t0,468($a0) li $t0,416 sw $t0,472($a0) li $t0,993 sw $t0,476($a0) li $t0,240 sw $t0,480($a0) li $t0,482 sw $t0,484($a0) li $t0,478 sw $t0,488($a0) li $t0,923 sw $t0,492($a0) li $t0,576 sw $t0,496($a0) li $t0,24 sw $t0,500($a0) li $t0,81 sw $t0,504($a0) li $t0,8 sw $t0,508($a0) #record systick lw $s6,20($s0) #bubsort li $s1,128 li $s2,0 #$s2=i,a0=v[] li $s3,0 #$s3=j for1: slt $t2,$s2,$s1 beq $t2,$zero,end addi $s3,$s2,-1 for2: bltz $s3,out2 sll $t2,$s3,2 add $t2,$a0,$t2 lw $t3,0($t2) lw $t4,4($t2) slt $t5,$t4,$t3 beq $t5,$zero,out2 sw $t4,0($t2) sw $t3,4($t2) addi $s3,$s3,-1 j for2 out2: addi $s2,$s2,1 j for1 end: lw $s7,20($s0) li $t0 0x000000ff sw $t0,12($s0) sub $s7,$s7,$s6 #start timer li $t0,0x00000003 sw $t0,8($s0) #TCON li $s5,0 li $s6,0 Loop: j Loop Interrupt: li $t0,0x00000001 #set TCON sw $t0,8($s0) beq $s5,$zero,pos_zero li $at,1 beq $s5,$at,pos_one li $at,2 beq $s5,$at,pos_two li $at,3 beq $s5,$at,pos_three pos_zero: li $s4,0x00000100 andi $t1,$s7,0x000f j number pos_one: li $s4,0x00000200 andi $t1,$s7,0x00f0 srl $t1,$t1,4 j number pos_two: li $s4,0x00000400 andi $t1,$s7,0x0f00 srl $t1,$t1,8 j number pos_three: li $s4,0x00000800 andi $t1,$s7,0xf000 srl $t1,$t1,12 number: li $at,0x00000000 beq $t1,$at,number0 li $at,0x00000001 beq $t1,$at,number1 li $at,0x00000002 beq $t1,$at,number2 li $at,0x00000003 beq $t1,$at,number3 li $at,0x00000004 beq $t1,$at,number4 li $at,0x00000005 beq $t1,$at,number5 li $at,0x00000006 beq $t1,$at,number6 li $at,0x00000007 beq $t1,$at,number7 li $at,0x00000008 beq $t1,$at,number8 li $at,0x00000009 beq $t1,$at,number9 li $at,0x0000000a beq $t1,$at,numberA li $at,0x0000000b beq $t1,$at,numberB li $at,0x0000000c beq $t1,$at,numberC li $at,0x0000000d beq $t1,$at,numberD li $at,0x0000000e beq $t1,$at,numberE li $at,0x0000000f beq $t1,$at,numberF number0: ori $s4,$s4,0x00c0 j show number1: ori $s4,$s4,0x00f9 j show number2: ori $s4,$s4,0x00a4 j show number3: ori $s4,$s4,0x00b0 j show number4: ori $s4,$s4,0x0099 j show number5: ori $s4,$s4,0x0092 j show number6: ori $s4,$s4,0x0082 j show number7: ori $s4,$s4,0x00f8 j show number8: ori $s4,$s4,0x0080 j show number9: ori $s4,$s4,0x0090 j show numberA: ori $s4,$s4,0x0088 j show numberB: ori $s4,$s4,0x0083 j show numberC: ori $s4,$s4,0x00c6 j show numberD: ori $s4,$s4,0x00a1 j show numberE: ori $s4,$s4,0x0086 j show numberF: ori $s4,$s4,0x008e show: li $at,4 addi $s5,$s5,1 sw $s4,16($s0) bne $s5,$at,continue addi $s6,$s6,1 li $at,5 li $s5,0 bne $s6,$at,continue sw $zero,8($s0) sw $zero,12($s0) li $t0,0x00000fff sw $t0,16($s0) jr $k0 continue: li $t0,0x00000003 sw $t0,8($s0) jr $k0 Exception: nop nop nop jr $k0
[bits 16] repne lodsw ; out: f2 ad repnz lodsd ; out: 66 f2 ad rep stosb ; out: f3 aa repe cmpsb ; out: f3 a6 repz movsb ; out: f3 a4
SECTION "Test",CODE[0] sub (hl) sub a,(ix+2) sub a,(iy-2) sub a,b sub a,c sub a,d sub a,e sub a,h sub a,l sub a,a sub a,2
GameCornerPrizeRoom_Object: db $f ; border block def_warps warp 4, 7, 9, LAST_MAP warp 5, 7, 9, LAST_MAP def_signs sign 2, 2, 3 ; CeladonPrizeRoomText3 sign 4, 2, 4 ; CeladonPrizeRoomText4 sign 6, 2, 5 ; CeladonPrizeRoomText5 def_objects object SPRITE_BALDING_GUY, 1, 4, STAY, NONE, 1 ; person object SPRITE_GAMBLER, 7, 3, WALK, LEFT_RIGHT, 2 ; person def_warps_to GAME_CORNER_PRIZE_ROOM
; A014728: Squares of odd Fibonacci numbers. ; 1,1,9,25,169,441,3025,7921,54289,142129,974169,2550409,17480761,45765225,313679521,821223649,5628750625,14736260449,101003831721,264431464441,1812440220361,4745030099481,32522920134769 seq $0,254962 ; Indices of hexagonal numbers (A000384) that are also centered pentagonal numbers (A005891). div $0,-2 mul $0,-1 div $0,5 mul $0,8 add $0,1
#ifndef MPSKIT_MODELS_BOSE_HUBBARD_1D #define MPSKIT_MODELS_BOSE_HUBBARD_1D #include "../json.hpp" #include "../types.hpp" #include "bosonic_1d.hpp" class BoseHubbard1D : public Bosonic1D { protected: Real m_J; Real m_U; Real m_mu; public: explicit BoseHubbard1D(int L, bool periodic, bool conserve_N, int max_N, const Real &J, const Real &U, const Real &mu); explicit BoseHubbard1D(const json &js); const Real &getJ() const; const Real &getU() const; const Real &getMu() const; }; #endif /* MPSKIT_MODELS_BOSE_HUBBARD_1D */
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r8 push %rbp push %rbx push %rdi push %rdx // Faulty Load lea addresses_normal+0x19e1f, %rbx nop and $53765, %rdi movups (%rbx), %xmm3 vpextrq $1, %xmm3, %r8 lea oracles, %rbp and $0xff, %r8 shlq $12, %r8 mov (%rbp,%r8,1), %r8 pop %rdx pop %rdi pop %rbx pop %rbp pop %r8 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal', 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_normal', 'congruent': 0}} <gen_prepare_buffer> {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
//===- AIECreatePacketFlows.cpp ---------------------------------*- C++ -*-===// // // This file is licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // // (c) Copyright 2019 Xilinx Inc. // //===----------------------------------------------------------------------===// #include "aie/AIEDialect.h" #include "aie/AIENetlistAnalysis.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Location.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Pass/Pass.h" #include "mlir/Transforms/DialectConversion.h" #include "mlir/Translation.h" #include "llvm/ADT/Twine.h" #define DEBUG_TYPE "aie-create-packet-flows" using namespace mlir; using namespace xilinx; using namespace xilinx::AIE; template <typename MyOp> struct AIEOpRemoval : public OpConversionPattern<MyOp> { using OpConversionPattern<MyOp>::OpConversionPattern; using OpAdaptor = typename MyOp::Adaptor; ModuleOp &module; AIEOpRemoval(MLIRContext *context, ModuleOp &m, PatternBenefit benefit = 1) : OpConversionPattern<MyOp>(context, benefit), module(m) {} LogicalResult matchAndRewrite(MyOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override { Operation *Op = op.getOperation(); rewriter.eraseOp(Op); return success(); } }; // A port on a switch is identified by the tile and port name. typedef std::pair<Operation *, Port> PhysPort; int getAvailableDestChannel(SmallVector<std::pair<Connect, int>, 8> &connects, Port sourcePort, int flowID, WireBundle destBundle) { if (connects.size() == 0) return 0; int numChannels; if (destBundle == WireBundle::North) numChannels = 6; else if (destBundle == WireBundle::South || destBundle == WireBundle::East || destBundle == WireBundle::West) numChannels = 4; else numChannels = 2; // look for existing connect that has a matching destination for (int i = 0; i < numChannels; i++) { Port port = std::make_pair(destBundle, i); int countFlows = 0; for (auto conn : connects) { Port connDest = conn.first.second; // Since we are doing packet-switched routing, dest ports can be shared // among multiple sources. Therefore, we don't need to worry about // checking the same source if (connDest == port) countFlows++; } // Since a mask has 5 bits, there can only be 32 logical streams flow // through a port // TODO: what about packet-switched flow that uses nested header? if (countFlows > 0 && countFlows < 32) return i; } // if not, look for available destination port for (int i = 0; i < numChannels; i++) { Port port = std::make_pair(destBundle, i); SmallVector<Port, 8> ports; for (auto connect : connects) ports.push_back(connect.first.second); if (std::find(ports.begin(), ports.end(), port) == ports.end()) return i; } return -1; } void update_coordinates(int &xCur, int &yCur, WireBundle move) { if (move == WireBundle::East) { xCur = xCur + 1; // yCur = yCur; } else if (move == WireBundle::West) { xCur = xCur - 1; // yCur = yCur; } else if (move == WireBundle::North) { // xCur = xCur; yCur = yCur + 1; } else if (move == WireBundle::South) { // xCur = xCur; yCur = yCur - 1; } } // Build a packet-switched route from the sourse to the destination with the // given ID. The route is recorded in the given map of switchboxes. void buildPSRoute( int xSrc, int ySrc, Port sourcePort, int xDest, int yDest, Port destPort, int flowID, DenseMap<std::pair<int, int>, SmallVector<std::pair<Connect, int>, 8>> &switchboxes) { int xCur = xSrc; int yCur = ySrc; WireBundle curBundle; int curChannel; int xLast, yLast; WireBundle lastBundle; Port lastPort = sourcePort; SmallVector<std::pair<int, int>, 4> congestion; LLVM_DEBUG(llvm::dbgs() << "Build route ID " << flowID << ": " << xSrc << " " << ySrc << " --> " << xDest << " " << yDest << '\n'); // traverse horizontally, then vertically while (!((xCur == xDest) && (yCur == yDest))) { LLVM_DEBUG(llvm::dbgs() << "Tile " << xCur << " " << yCur << " "); auto curCoord = std::make_pair(xCur, yCur); xLast = xCur; yLast = yCur; SmallVector<WireBundle, 4> moves; if (xCur < xDest) moves.push_back(WireBundle::East); if (xCur > xDest) moves.push_back(WireBundle::West); if (yCur < yDest) moves.push_back(WireBundle::North); if (yCur > yDest) moves.push_back(WireBundle::South); if (std::find(moves.begin(), moves.end(), WireBundle::East) == moves.end()) moves.push_back(WireBundle::East); if (std::find(moves.begin(), moves.end(), WireBundle::West) == moves.end()) moves.push_back(WireBundle::West); if (std::find(moves.begin(), moves.end(), WireBundle::North) == moves.end()) moves.push_back(WireBundle::North); if (std::find(moves.begin(), moves.end(), WireBundle::South) == moves.end()) moves.push_back(WireBundle::South); for (unsigned i = 0; i < moves.size(); i++) { WireBundle move = moves[i]; curChannel = getAvailableDestChannel(switchboxes[curCoord], lastPort, flowID, move); if (curChannel == -1) continue; if (move == lastBundle) continue; update_coordinates(xCur, yCur, move); if (std::find(congestion.begin(), congestion.end(), std::make_pair(xCur, yCur)) != congestion.end()) continue; curBundle = move; lastBundle = (move == WireBundle::East) ? WireBundle::West : (move == WireBundle::West) ? WireBundle::East : (move == WireBundle::North) ? WireBundle::South : (move == WireBundle::South) ? WireBundle::North : lastBundle; break; } assert(curChannel >= 0 && "Could not find available destination port!"); if (curChannel == -1) { congestion.push_back( std::make_pair(xLast, yLast)); // this switchbox is congested switchboxes[curCoord].pop_back(); // back up, remove the last connection } else { LLVM_DEBUG(llvm::dbgs() << stringifyWireBundle(lastPort.first) << " " << lastPort.second << " -> " << stringifyWireBundle(curBundle) << " " << curChannel << "\n"); Port curPort = std::make_pair(curBundle, curChannel); Connect connect = std::make_pair(lastPort, curPort); // If there is no connection with this ID going where we want to go.. if (std::find(switchboxes[curCoord].begin(), switchboxes[curCoord].end(), std::make_pair(connect, flowID)) == switchboxes[curCoord].end()) // then add one. switchboxes[curCoord].push_back(std::make_pair(connect, flowID)); lastPort = std::make_pair(lastBundle, curChannel); } } LLVM_DEBUG(llvm::dbgs() << "Tile " << xCur << " " << yCur << " "); LLVM_DEBUG(llvm::dbgs() << stringifyWireBundle(lastPort.first) << " " << lastPort.second << " -> " << stringifyWireBundle(curBundle) << " " << curChannel << "\n"); switchboxes[std::make_pair(xCur, yCur)].push_back( std::make_pair(std::make_pair(lastPort, destPort), flowID)); } SwitchboxOp getOrCreateSwitchbox(OpBuilder &builder, TileOp tile) { for (auto i : tile.result().getUsers()) { if (llvm::isa<SwitchboxOp>(*i)) { return llvm::cast<SwitchboxOp>(*i); } } return builder.create<SwitchboxOp>(builder.getUnknownLoc(), tile); } struct AIERoutePacketFlowsPass : public AIERoutePacketFlowsBase<AIERoutePacketFlowsPass> { // Map from tile coordinates to TileOp DenseMap<std::pair<int, int>, Operation *> tiles; Operation *getOrCreateTile(OpBuilder &builder, int col, int row) { auto index = std::make_pair(col, row); Operation *tileOp = tiles[index]; if (!tileOp) { auto tile = builder.create<TileOp>(builder.getUnknownLoc(), col, row); tileOp = tile.getOperation(); tiles[index] = tileOp; } return tileOp; } void runOnOperation() override { ModuleOp m = getOperation(); OpBuilder builder = OpBuilder::atBlockEnd(m.getBody()); ConversionTarget target(getContext()); // Some communication patterns: // - one-to-one // - one-to-many // + same flow (same port, same ID): broadcast/multicast // + different flows (same port, differnt IDs) // - many-to-one // + timeshare: single arbiter, different msels // - many-to-many // // Compute the mask for each LUT entry of a slave port // Aim to generate as few LUT entries as possible // Avoid creating packetswitch config as much as possible // We will use circuit-switch to pre-route the flows from the source swboxes // to the dest swboxes, and only use packet-switch to route at the dest // swboxes // Map from a port and flowID to DenseMap<std::pair<PhysPort, int>, SmallVector<PhysPort, 4>> packetFlows; SmallVector<std::pair<PhysPort, int>, 4> slavePorts; DenseMap<std::pair<PhysPort, int>, int> slaveAMSels; for (auto tileOp : m.getOps<TileOp>()) { int col = tileOp.colIndex(); int row = tileOp.rowIndex(); tiles[std::make_pair(col, row)] = tileOp; } // The logical model of all the switchboxes. DenseMap<std::pair<int, int>, SmallVector<std::pair<Connect, int>, 8>> switchboxes; for (auto pktflow : m.getOps<PacketFlowOp>()) { Region &r = pktflow.ports(); Block &b = r.front(); int flowID = pktflow.IDInt(); int xSrc, ySrc; Port sourcePort; for (Operation &Op : b.getOperations()) { if (PacketSourceOp pktSource = dyn_cast<PacketSourceOp>(Op)) { TileOp srcTile = dyn_cast<TileOp>(pktSource.tile().getDefiningOp()); xSrc = srcTile.colIndex(); ySrc = srcTile.rowIndex(); sourcePort = pktSource.port(); } else if (PacketDestOp pktDest = dyn_cast<PacketDestOp>(Op)) { TileOp destTile = dyn_cast<TileOp>(pktDest.tile().getDefiningOp()); int xDest = destTile.colIndex(); int yDest = destTile.rowIndex(); Port destPort = pktDest.port(); buildPSRoute(xSrc, ySrc, sourcePort, xDest, yDest, destPort, flowID, switchboxes); } } } LLVM_DEBUG(llvm::dbgs() << "Check switchboxes\n"); for (auto swbox : switchboxes) { int col = swbox.first.first; int row = swbox.first.second; Operation *tileOp = getOrCreateTile(builder, col, row); LLVM_DEBUG(llvm::dbgs() << "***switchbox*** " << col << " " << row << '\n'); SmallVector<std::pair<Connect, int>, 8> connects(swbox.second); for (auto connect : connects) { Port sourcePort = connect.first.first; Port destPort = connect.first.second; int flowID = connect.second; int nextCol = col, nextRow = row; update_coordinates(nextCol, nextRow, sourcePort.first); LLVM_DEBUG(llvm::dbgs() << "flowID " << flowID << ':' << stringifyWireBundle(sourcePort.first) << " " << sourcePort.second << " -> " << stringifyWireBundle(destPort.first) << " " << destPort.second << " tile " << nextCol << " " << nextRow << "\n"); auto sourceFlow = std::make_pair(std::make_pair(tileOp, sourcePort), flowID); packetFlows[sourceFlow].push_back(std::make_pair(tileOp, destPort)); slavePorts.push_back(sourceFlow); } } // amsel() // masterset() // packetrules() // rule() // Compute arbiter assignments. Each arbiter has four msels. // Therefore, the number of "logical" arbiters is 6 x 4 = 24 // A master port can only be associated with one arbiter // A map from Tile and master selectValue to the ports targetted by that // master select. DenseMap<std::pair<Operation *, int>, SmallVector<Port, 4>> masterAMSels; // Count of currently used logical arbiters for each tile. DenseMap<Operation *, int> amselValues; int numMsels = 4; int numArbiters = 6; // Check all multi-cast flows (same source, same ID). They should be // assigned the same arbiter and msel so that the flow can reach all the // destination ports at the same time For destination ports that appear in // different (multicast) flows, it should have a different <arbiterID, msel> // value pair for each flow for (auto packetFlow : packetFlows) { // The Source Tile of the flow Operation *tileOp = packetFlow.first.first.first; if (amselValues.count(tileOp) == 0) amselValues[tileOp] = 0; // arb0: 6*0, 6*1, 6*2, 6*3 // arb1: 6*0+1, 6*1+1, 6*2+1, 6*3+1 // arb2: 6*0+2, 6*1+2, 6*2+2, 6*3+2 // arb3: 6*0+3, 6*1+3, 6*2+3, 6*3+3 // arb4: 6*0+4, 6*1+4, 6*2+4, 6*3+4 // arb5: 6*0+5, 6*1+5, 6*2+5, 6*3+5 int amselValue = amselValues[tileOp]; assert(amselValue < numArbiters && "Could not allocate new arbiter!"); // Find existing arbiter assignment // If there is an assignment of an arbiter to a master port before, we // assign all the master ports here with the same arbiter but different // msel bool foundMatchedDest = false; for (auto map : masterAMSels) { if (map.first.first != tileOp) continue; amselValue = map.first.second; // check if same destinations // SmallVector<Port, 4> ports(map.second); SmallVector<Port, 4> ports( masterAMSels[std::make_pair(tileOp, amselValue)]); if (ports.size() != packetFlow.second.size()) continue; bool matched = true; for (auto dest : packetFlow.second) { Port port = dest.second; if (std::find(ports.begin(), ports.end(), port) == ports.end()) { matched = false; break; } } if (matched) { foundMatchedDest = true; break; } } if (!foundMatchedDest) { bool foundAMSelValue = false; for (int a = 0; a < numArbiters; a++) { for (int i = 0; i < numMsels; i++) { amselValue = a + i * numArbiters; if (masterAMSels.count(std::make_pair(tileOp, amselValue)) == 0) { foundAMSelValue = true; break; } } if (foundAMSelValue) break; } for (auto dest : packetFlow.second) { Port port = dest.second; masterAMSels[std::make_pair(tileOp, amselValue)].push_back(port); } } slaveAMSels[packetFlow.first] = amselValue; amselValues[tileOp] = amselValue % numArbiters; } // Compute the master set IDs // A map from a switchbox output port to the number of that port. DenseMap<PhysPort, SmallVector<int, 4>> mastersets; for (auto master : masterAMSels) { Operation *tileOp = master.first.first; assert(tileOp); int amselValue = master.first.second; for (auto port : master.second) { auto physPort = std::make_pair(tileOp, port); mastersets[physPort].push_back(amselValue); } } LLVM_DEBUG(llvm::dbgs() << "CHECK mastersets\n"); for (auto map : mastersets) { Operation *tileOp = map.first.first; WireBundle bundle = map.first.second.first; int channel = map.first.second.second; assert(tileOp); TileOp tile = dyn_cast<TileOp>(tileOp); LLVM_DEBUG(llvm::dbgs() << "master " << tile << " " << stringifyWireBundle(bundle) << " : " << channel << '\n'); for (auto value : map.second) LLVM_DEBUG(llvm::dbgs() << "amsel: " << value << '\n'); } // Compute mask values // Merging as many stream flows as possible // The flows must originate from the same source port and have different IDs // Two flows can be merged if they share the same destinations SmallVector<SmallVector<std::pair<PhysPort, int>, 4>, 4> slaveGroups; SmallVector<std::pair<PhysPort, int>, 4> workList(slavePorts); while (!workList.empty()) { auto slave1 = workList.pop_back_val(); Port slavePort1 = slave1.first.second; bool foundgroup = false; for (auto &group : slaveGroups) { auto slave2 = group.front(); Port slavePort2 = slave2.first.second; if (slavePort1 != slavePort2) continue; bool matched = true; auto dests1 = packetFlows[slave1]; auto dests2 = packetFlows[slave2]; if (dests1.size() != dests2.size()) continue; for (auto dest1 : dests1) { if (std::find(dests2.begin(), dests2.end(), dest1) == dests2.end()) { matched = false; break; } } if (matched) { group.push_back(slave1); foundgroup = true; break; } } if (!foundgroup) { SmallVector<std::pair<PhysPort, int>, 4> group({slave1}); slaveGroups.push_back(group); } } DenseMap<std::pair<PhysPort, int>, int> slaveMasks; for (auto group : slaveGroups) { // Iterate over all the ID values in a group // If bit n-th (n <= 5) of an ID value differs from bit n-th of another ID // value, the bit position should be "don't care", and we will set the // mask bit of that position to 0 int mask[5] = {-1, -1, -1, -1, -1}; for (auto port : group) { int ID = port.second; for (int i = 0; i < 5; i++) { if (mask[i] == -1) mask[i] = ((ID >> i) & 0x1); else if (mask[i] != ((ID >> i) & 0x1)) mask[i] = 2; // found bit difference --> mark as "don't care" } } int maskValue = 0; for (int i = 4; i >= 0; i--) { if (mask[i] == 2) // don't care mask[i] = 0; else mask[i] = 1; maskValue = (maskValue << 1) + mask[i]; } for (auto port : group) slaveMasks[port] = maskValue; } LLVM_DEBUG(llvm::dbgs() << "CHECK Slave Masks\n"); for (auto map : slaveMasks) { auto port = map.first.first; TileOp tile = dyn_cast<TileOp>(port.first); WireBundle bundle = port.second.first; int channel = port.second.second; int ID = map.first.second; int mask = map.second; LLVM_DEBUG(llvm::dbgs() << "Port " << tile << " " << stringifyWireBundle(bundle) << " " << channel << '\n'); LLVM_DEBUG(llvm::dbgs() << "Mask " << "0x" << llvm::Twine::utohexstr(mask) << '\n'); LLVM_DEBUG(llvm::dbgs() << "ID " << "0x" << llvm::Twine::utohexstr(ID) << '\n'); for (int i = 0; i < 31; i++) { if ((i & mask) == (ID & mask)) LLVM_DEBUG(llvm::dbgs() << "matches flow ID " << "0x" << llvm::Twine::utohexstr(i) << '\n'); } } // Realize the routes in MLIR for (auto map : tiles) { Operation *tileOp = map.second; TileOp tile = dyn_cast<TileOp>(tileOp); // Create a switchbox for the routes and insert inside it. builder.setInsertionPointAfter(tileOp); SwitchboxOp swbox = getOrCreateSwitchbox(builder, tile); swbox.ensureTerminator(swbox.connections(), builder, builder.getUnknownLoc()); Block &b = swbox.connections().front(); builder.setInsertionPoint(b.getTerminator()); std::vector<bool> amselOpNeededVector(32); for (auto map : mastersets) { if (tileOp != map.first.first) continue; for (auto value : map.second) { amselOpNeededVector[value] = true; } } // Create all the amsel Ops DenseMap<int, AMSelOp> amselOps; for (int i = 0; i < 32; i++) { if (amselOpNeededVector[i]) { int arbiterID = i % numArbiters; int msel = i / numArbiters; AMSelOp amsel = builder.create<AMSelOp>(builder.getUnknownLoc(), arbiterID, msel); amselOps[i] = amsel; } } // Create all the master set Ops // First collect the master sets for this tile. SmallVector<Port, 4> tileMasters; for (auto map : mastersets) { if (tileOp != map.first.first) continue; tileMasters.push_back(map.first.second); } // Sort them so we get a reasonable order std::sort(tileMasters.begin(), tileMasters.end()); for (auto tileMaster : tileMasters) { WireBundle bundle = tileMaster.first; int channel = tileMaster.second; SmallVector<int, 4> msels = mastersets[std::make_pair(tileOp, tileMaster)]; SmallVector<Value, 4> amsels; for (auto msel : msels) { assert(amselOps.count(msel) == 1); amsels.push_back(amselOps[msel]); } builder.create<MasterSetOp>(builder.getUnknownLoc(), builder.getIndexType(), bundle, channel, amsels); } // Generate the packet rules DenseMap<Port, PacketRulesOp> slaveRules; for (auto group : slaveGroups) { builder.setInsertionPoint(b.getTerminator()); auto port = group.front().first; if (tileOp != port.first) continue; WireBundle bundle = port.second.first; int channel = port.second.second; auto slave = port.second; int mask = slaveMasks[group.front()]; int ID = group.front().second & mask; // Verify that we actually map all the ID's correctly. for (auto slave : group) { assert((slave.second & mask) == ID); } Value amsel = amselOps[slaveAMSels[group.front()]]; PacketRulesOp packetrules; if (slaveRules.count(slave) == 0) { packetrules = builder.create<PacketRulesOp>(builder.getUnknownLoc(), bundle, channel); packetrules.ensureTerminator(packetrules.rules(), builder, builder.getUnknownLoc()); slaveRules[slave] = packetrules; } else packetrules = slaveRules[slave]; Block &rules = packetrules.rules().front(); builder.setInsertionPoint(rules.getTerminator()); builder.create<PacketRuleOp>(builder.getUnknownLoc(), mask, ID, amsel); } } OwningRewritePatternList patterns(&getContext()); patterns.add<AIEOpRemoval<PacketFlowOp> >(m.getContext(), m); if (failed(applyPartialConversion(m, target, std::move(patterns)))) signalPassFailure(); } }; std::unique_ptr<OperationPass<ModuleOp>> xilinx::AIE::createAIERoutePacketFlowsPass() { return std::make_unique<AIERoutePacketFlowsPass>(); }
// Copyright 2010 Google Inc. All Rights Reserved. // Author: rays@google.com (Ray Smith) /////////////////////////////////////////////////////////////////////// // File: shapetable.cpp // Description: Class to map a classifier shape index to unicharset // indices and font indices. // Author: Ray Smith // Created: Tue Nov 02 15:31:32 PDT 2010 // // (C) Copyright 2010, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include "shapetable.h" #include "bitvector.h" #include "fontinfo.h" #include "intfeaturespace.h" #include "strngs.h" #include "unicharset.h" #include "unicity_table.h" namespace tesseract { // Helper function to get the index of the first result with the required // unichar_id. If the results are sorted by rating, this will also be the // best result with the required unichar_id. // Returns -1 if the unichar_id is not found int ShapeRating::FirstResultWithUnichar( const GenericVector<ShapeRating>& results, const ShapeTable& shape_table, UNICHAR_ID unichar_id) { for (int r = 0; r < results.size(); ++r) { int shape_id = results[r].shape_id; const Shape& shape = shape_table.GetShape(shape_id); if (shape.ContainsUnichar(unichar_id)) { return r; } } return -1; } // Helper function to get the index of the first result with the required // unichar_id. If the results are sorted by rating, this will also be the // best result with the required unichar_id. // Returns -1 if the unichar_id is not found int UnicharRating::FirstResultWithUnichar( const GenericVector<UnicharRating>& results, UNICHAR_ID unichar_id) { for (int r = 0; r < results.size(); ++r) { if (results[r].unichar_id == unichar_id) return r; } return -1; } // Writes to the given file. Returns false in case of error. bool UnicharAndFonts::Serialize(FILE* fp) const { if (fwrite(&unichar_id, sizeof(unichar_id), 1, fp) != 1) return false; if (!font_ids.Serialize(fp)) return false; return true; } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool UnicharAndFonts::DeSerialize(bool swap, FILE* fp) { if (fread(&unichar_id, sizeof(unichar_id), 1, fp) != 1) return false; if (swap) ReverseN(&unichar_id, sizeof(unichar_id)); if (!font_ids.DeSerialize(swap, fp)) return false; return true; } // Sort function to sort a pair of UnicharAndFonts by unichar_id. int UnicharAndFonts::SortByUnicharId(const void* v1, const void* v2) { const UnicharAndFonts* p1 = reinterpret_cast<const UnicharAndFonts*>(v1); const UnicharAndFonts* p2 = reinterpret_cast<const UnicharAndFonts*>(v2); return p1->unichar_id - p2->unichar_id; } // Writes to the given file. Returns false in case of error. bool Shape::Serialize(FILE* fp) const { uinT8 sorted = unichars_sorted_; if (fwrite(&sorted, sizeof(sorted), 1, fp) != 1) return false; if (!unichars_.SerializeClasses(fp)) return false; return true; } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool Shape::DeSerialize(bool swap, FILE* fp) { uinT8 sorted; if (fread(&sorted, sizeof(sorted), 1, fp) != 1) return false; unichars_sorted_ = sorted != 0; if (!unichars_.DeSerializeClasses(swap, fp)) return false; return true; } // Adds a font_id for the given unichar_id. If the unichar_id is not // in the shape, it is added. void Shape::AddToShape(int unichar_id, int font_id) { for (int c = 0; c < unichars_.size(); ++c) { if (unichars_[c].unichar_id == unichar_id) { // Found the unichar in the shape table. GenericVector<int>& font_list = unichars_[c].font_ids; for (int f = 0; f < font_list.size(); ++f) { if (font_list[f] == font_id) return; // Font is already there. } font_list.push_back(font_id); return; } } // Unichar_id is not in shape, so add it to shape. unichars_.push_back(UnicharAndFonts(unichar_id, font_id)); unichars_sorted_ = unichars_.size() <= 1; } // Adds everything in other to this. void Shape::AddShape(const Shape& other) { for (int c = 0; c < other.unichars_.size(); ++c) { for (int f = 0; f < other.unichars_[c].font_ids.size(); ++f) { AddToShape(other.unichars_[c].unichar_id, other.unichars_[c].font_ids[f]); } } unichars_sorted_ = unichars_.size() <= 1; } // Returns true if the shape contains the given unichar_id, font_id pair. bool Shape::ContainsUnicharAndFont(int unichar_id, int font_id) const { for (int c = 0; c < unichars_.size(); ++c) { if (unichars_[c].unichar_id == unichar_id) { // Found the unichar, so look for the font. GenericVector<int>& font_list = unichars_[c].font_ids; for (int f = 0; f < font_list.size(); ++f) { if (font_list[f] == font_id) return true; } return false; } } return false; } // Returns true if the shape contains the given unichar_id, ignoring font. bool Shape::ContainsUnichar(int unichar_id) const { for (int c = 0; c < unichars_.size(); ++c) { if (unichars_[c].unichar_id == unichar_id) { return true; } } return false; } // Returns true if the shape contains the given font, ignoring unichar_id. bool Shape::ContainsFont(int font_id) const { for (int c = 0; c < unichars_.size(); ++c) { GenericVector<int>& font_list = unichars_[c].font_ids; for (int f = 0; f < font_list.size(); ++f) { if (font_list[f] == font_id) return true; } } return false; } // Returns true if the shape contains the given font properties, ignoring // unichar_id. bool Shape::ContainsFontProperties(const FontInfoTable& font_table, uinT32 properties) const { for (int c = 0; c < unichars_.size(); ++c) { GenericVector<int>& font_list = unichars_[c].font_ids; for (int f = 0; f < font_list.size(); ++f) { if (font_table.get(font_list[f]).properties == properties) return true; } } return false; } // Returns true if the shape contains multiple different font properties, // ignoring unichar_id. bool Shape::ContainsMultipleFontProperties( const FontInfoTable& font_table) const { uinT32 properties = font_table.get(unichars_[0].font_ids[0]).properties; for (int c = 0; c < unichars_.size(); ++c) { GenericVector<int>& font_list = unichars_[c].font_ids; for (int f = 0; f < font_list.size(); ++f) { if (font_table.get(font_list[f]).properties != properties) return true; } } return false; } // Returns true if this shape is equal to other (ignoring order of unichars // and fonts). bool Shape::operator==(const Shape& other) const { return IsSubsetOf(other) && other.IsSubsetOf(*this); } // Returns true if this is a subset (including equal) of other. bool Shape::IsSubsetOf(const Shape& other) const { for (int c = 0; c < unichars_.size(); ++c) { int unichar_id = unichars_[c].unichar_id; const GenericVector<int>& font_list = unichars_[c].font_ids; for (int f = 0; f < font_list.size(); ++f) { if (!other.ContainsUnicharAndFont(unichar_id, font_list[f])) return false; } } return true; } // Returns true if the lists of unichar ids are the same in this and other, // ignoring fonts. // NOT const, as it will sort the unichars on demand. bool Shape::IsEqualUnichars(Shape* other) { if (unichars_.size() != other->unichars_.size()) return false; if (!unichars_sorted_) SortUnichars(); if (!other->unichars_sorted_) other->SortUnichars(); for (int c = 0; c < unichars_.size(); ++c) { if (unichars_[c].unichar_id != other->unichars_[c].unichar_id) return false; } return true; } // Sorts the unichars_ vector by unichar. void Shape::SortUnichars() { unichars_.sort(UnicharAndFonts::SortByUnicharId); unichars_sorted_ = true; } ShapeTable::ShapeTable() : unicharset_(NULL), num_fonts_(0) { } ShapeTable::ShapeTable(const UNICHARSET& unicharset) : unicharset_(&unicharset), num_fonts_(0) { } // Writes to the given file. Returns false in case of error. bool ShapeTable::Serialize(FILE* fp) const { if (!shape_table_.Serialize(fp)) return false; return true; } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool ShapeTable::DeSerialize(bool swap, FILE* fp) { if (!shape_table_.DeSerialize(swap, fp)) return false; num_fonts_ = 0; return true; } // Returns the number of fonts used in this ShapeTable, computing it if // necessary. int ShapeTable::NumFonts() const { if (num_fonts_ <= 0) { for (int shape_id = 0; shape_id < shape_table_.size(); ++shape_id) { const Shape& shape = *shape_table_[shape_id]; for (int c = 0; c < shape.size(); ++c) { for (int f = 0; f < shape[c].font_ids.size(); ++f) { if (shape[c].font_ids[f] >= num_fonts_) num_fonts_ = shape[c].font_ids[f] + 1; } } } } return num_fonts_; } // Re-indexes the class_ids in the shapetable according to the given map. // Useful in conjunction with set_unicharset. void ShapeTable::ReMapClassIds(const GenericVector<int>& unicharset_map) { for (int shape_id = 0; shape_id < shape_table_.size(); ++shape_id) { Shape* shape = shape_table_[shape_id]; for (int c = 0; c < shape->size(); ++c) { shape->SetUnicharId(c, unicharset_map[(*shape)[c].unichar_id]); } } } // Returns a string listing the classes/fonts in a shape. STRING ShapeTable::DebugStr(int shape_id) const { if (shape_id < 0 || shape_id >= shape_table_.size()) return STRING("INVALID_UNICHAR_ID"); const Shape& shape = GetShape(shape_id); STRING result; result.add_str_int("Shape", shape_id); if (shape.size() > 100) { result.add_str_int(" Num unichars=", shape.size()); return result; } for (int c = 0; c < shape.size(); ++c) { result.add_str_int(" c_id=", shape[c].unichar_id); result += "="; result += unicharset_->id_to_unichar(shape[c].unichar_id); if (shape.size() < 10) { result.add_str_int(", ", shape[c].font_ids.size()); result += " fonts ="; int num_fonts = shape[c].font_ids.size(); if (num_fonts > 10) { result.add_str_int(" ", shape[c].font_ids[0]); result.add_str_int(" ... ", shape[c].font_ids[num_fonts - 1]); } else { for (int f = 0; f < num_fonts; ++f) { result.add_str_int(" ", shape[c].font_ids[f]); } } } } return result; } // Returns a debug string summarizing the table. STRING ShapeTable::SummaryStr() const { int max_unichars = 0; int num_multi_shapes = 0; int num_master_shapes = 0; for (int s = 0; s < shape_table_.size(); ++s) { if (MasterDestinationIndex(s) != s) continue; ++num_master_shapes; int shape_size = GetShape(s).size(); if (shape_size > 1) ++num_multi_shapes; if (shape_size > max_unichars) max_unichars = shape_size; } STRING result; result.add_str_int("Number of shapes = ", num_master_shapes); result.add_str_int(" max unichars = ", max_unichars); result.add_str_int(" number with multiple unichars = ", num_multi_shapes); return result; } // Adds a new shape starting with the given unichar_id and font_id. // Returns the assigned index. int ShapeTable::AddShape(int unichar_id, int font_id) { int index = shape_table_.size(); Shape* shape = new Shape; shape->AddToShape(unichar_id, font_id); shape_table_.push_back(shape); num_fonts_ = MAX(num_fonts_, font_id + 1); return index; } // Adds a copy of the given shape unless it is already present. // Returns the assigned index or index of existing shape if already present. int ShapeTable::AddShape(const Shape& other) { int index; for (index = 0; index < shape_table_.size() && !(other == *shape_table_[index]); ++index) continue; if (index == shape_table_.size()) { Shape* shape = new Shape(other); shape_table_.push_back(shape); } num_fonts_ = 0; return index; } // Removes the shape given by the shape index. void ShapeTable::DeleteShape(int shape_id) { delete shape_table_[shape_id]; shape_table_[shape_id] = NULL; shape_table_.remove(shape_id); } // Adds a font_id to the given existing shape index for the given // unichar_id. If the unichar_id is not in the shape, it is added. void ShapeTable::AddToShape(int shape_id, int unichar_id, int font_id) { Shape& shape = *shape_table_[shape_id]; shape.AddToShape(unichar_id, font_id); num_fonts_ = MAX(num_fonts_, font_id + 1); } // Adds the given shape to the existing shape with the given index. void ShapeTable::AddShapeToShape(int shape_id, const Shape& other) { Shape& shape = *shape_table_[shape_id]; shape.AddShape(other); num_fonts_ = 0; } // Returns the id of the shape that contains the given unichar and font. // If not found, returns -1. // If font_id < 0, the font_id is ignored and the first shape that matches // the unichar_id is returned. int ShapeTable::FindShape(int unichar_id, int font_id) const { for (int s = 0; s < shape_table_.size(); ++s) { const Shape& shape = GetShape(s); for (int c = 0; c < shape.size(); ++c) { if (shape[c].unichar_id == unichar_id) { if (font_id < 0) return s; // We don't care about the font. for (int f = 0; f < shape[c].font_ids.size(); ++f) { if (shape[c].font_ids[f] == font_id) return s; } } } } return -1; } // Returns the first unichar_id and font_id in the given shape. void ShapeTable::GetFirstUnicharAndFont(int shape_id, int* unichar_id, int* font_id) const { const UnicharAndFonts& unichar_and_fonts = (*shape_table_[shape_id])[0]; *unichar_id = unichar_and_fonts.unichar_id; *font_id = unichar_and_fonts.font_ids[0]; } // Expands all the classes/fonts in the shape individually to build // a ShapeTable. int ShapeTable::BuildFromShape(const Shape& shape, const ShapeTable& master_shapes) { BitVector shape_map(master_shapes.NumShapes()); for (int u_ind = 0; u_ind < shape.size(); ++u_ind) { for (int f_ind = 0; f_ind < shape[u_ind].font_ids.size(); ++f_ind) { int c = shape[u_ind].unichar_id; int f = shape[u_ind].font_ids[f_ind]; int master_id = master_shapes.FindShape(c, f); if (master_id >= 0) { shape_map.SetBit(master_id); } else if (FindShape(c, f) < 0) { AddShape(c, f); } } } int num_masters = 0; for (int s = 0; s < master_shapes.NumShapes(); ++s) { if (shape_map[s]) { AddShape(master_shapes.GetShape(s)); ++num_masters; } } return num_masters; } // Returns true if the shapes are already merged. bool ShapeTable::AlreadyMerged(int shape_id1, int shape_id2) const { return MasterDestinationIndex(shape_id1) == MasterDestinationIndex(shape_id2); } // Returns true if any shape contains multiple unichars. bool ShapeTable::AnyMultipleUnichars() const { int num_shapes = NumShapes(); for (int s1 = 0; s1 < num_shapes; ++s1) { if (MasterDestinationIndex(s1) != s1) continue; if (GetShape(s1).size() > 1) return true; } return false; } // Returns the maximum number of unichars over all shapes. int ShapeTable::MaxNumUnichars() const { int max_num_unichars = 0; int num_shapes = NumShapes(); for (int s = 0; s < num_shapes; ++s) { if (GetShape(s).size() > max_num_unichars) max_num_unichars = GetShape(s).size(); } return max_num_unichars; } // Merges shapes with a common unichar over the [start, end) interval. // Assumes single unichar per shape. void ShapeTable::ForceFontMerges(int start, int end) { for (int s1 = start; s1 < end; ++s1) { if (MasterDestinationIndex(s1) == s1 && GetShape(s1).size() == 1) { int unichar_id = GetShape(s1)[0].unichar_id; for (int s2 = s1 + 1; s2 < end; ++s2) { if (MasterDestinationIndex(s2) == s2 && GetShape(s2).size() == 1 && unichar_id == GetShape(s2)[0].unichar_id) { MergeShapes(s1, s2); } } } } ShapeTable compacted(*unicharset_); compacted.AppendMasterShapes(*this, NULL); *this = compacted; } // Returns the number of unichars in the master shape. int ShapeTable::MasterUnicharCount(int shape_id) const { int master_id = MasterDestinationIndex(shape_id); return GetShape(master_id).size(); } // Returns the sum of the font counts in the master shape. int ShapeTable::MasterFontCount(int shape_id) const { int master_id = MasterDestinationIndex(shape_id); const Shape& shape = GetShape(master_id); int font_count = 0; for (int c = 0; c < shape.size(); ++c) { font_count += shape[c].font_ids.size(); } return font_count; } // Returns the number of unichars that would result from merging the shapes. int ShapeTable::MergedUnicharCount(int shape_id1, int shape_id2) const { // Do it the easy way for now. int master_id1 = MasterDestinationIndex(shape_id1); int master_id2 = MasterDestinationIndex(shape_id2); Shape combined_shape(*shape_table_[master_id1]); combined_shape.AddShape(*shape_table_[master_id2]); return combined_shape.size(); } // Merges two shape_ids, leaving shape_id2 marked as merged. void ShapeTable::MergeShapes(int shape_id1, int shape_id2) { int master_id1 = MasterDestinationIndex(shape_id1); int master_id2 = MasterDestinationIndex(shape_id2); // Point master_id2 (and all merged shapes) to master_id1. shape_table_[master_id2]->set_destination_index(master_id1); // Add all the shapes of master_id2 to master_id1. shape_table_[master_id1]->AddShape(*shape_table_[master_id2]); } // Swaps two shape_ids. void ShapeTable::SwapShapes(int shape_id1, int shape_id2) { Shape* tmp = shape_table_[shape_id1]; shape_table_[shape_id1] = shape_table_[shape_id2]; shape_table_[shape_id2] = tmp; } // Returns the destination of this shape, (if merged), taking into account // the fact that the destination may itself have been merged. int ShapeTable::MasterDestinationIndex(int shape_id) const { int dest_id = shape_table_[shape_id]->destination_index(); if (dest_id == shape_id || dest_id < 0) return shape_id; // Is master already. int master_id = shape_table_[dest_id]->destination_index(); if (master_id == dest_id || master_id < 0) return dest_id; // Dest is the master and shape_id points to it. master_id = MasterDestinationIndex(master_id); return master_id; } // Returns false if the unichars in neither shape is a subset of the other. bool ShapeTable::SubsetUnichar(int shape_id1, int shape_id2) const { const Shape& shape1 = GetShape(shape_id1); const Shape& shape2 = GetShape(shape_id2); int c1, c2; for (c1 = 0; c1 < shape1.size(); ++c1) { int unichar_id1 = shape1[c1].unichar_id; if (!shape2.ContainsUnichar(unichar_id1)) break; } for (c2 = 0; c2 < shape2.size(); ++c2) { int unichar_id2 = shape2[c2].unichar_id; if (!shape1.ContainsUnichar(unichar_id2)) break; } return c1 == shape1.size() || c2 == shape2.size(); } // Returns false if the unichars in neither shape is a subset of the other. bool ShapeTable::MergeSubsetUnichar(int merge_id1, int merge_id2, int shape_id) const { const Shape& merge1 = GetShape(merge_id1); const Shape& merge2 = GetShape(merge_id2); const Shape& shape = GetShape(shape_id); int cm1, cm2, cs; for (cs = 0; cs < shape.size(); ++cs) { int unichar_id = shape[cs].unichar_id; if (!merge1.ContainsUnichar(unichar_id) && !merge2.ContainsUnichar(unichar_id)) break; // Shape is not a subset of the merge. } for (cm1 = 0; cm1 < merge1.size(); ++cm1) { int unichar_id1 = merge1[cm1].unichar_id; if (!shape.ContainsUnichar(unichar_id1)) break; // Merge is not a subset of shape } for (cm2 = 0; cm2 < merge2.size(); ++cm2) { int unichar_id2 = merge2[cm2].unichar_id; if (!shape.ContainsUnichar(unichar_id2)) break; // Merge is not a subset of shape } return cs == shape.size() || (cm1 == merge1.size() && cm2 == merge2.size()); } // Returns true if the unichar sets are equal between the shapes. bool ShapeTable::EqualUnichars(int shape_id1, int shape_id2) const { const Shape& shape1 = GetShape(shape_id1); const Shape& shape2 = GetShape(shape_id2); for (int c1 = 0; c1 < shape1.size(); ++c1) { int unichar_id1 = shape1[c1].unichar_id; if (!shape2.ContainsUnichar(unichar_id1)) return false; } for (int c2 = 0; c2 < shape2.size(); ++c2) { int unichar_id2 = shape2[c2].unichar_id; if (!shape1.ContainsUnichar(unichar_id2)) return false; } return true; } // Returns true if the unichar sets are equal between the shapes. bool ShapeTable::MergeEqualUnichars(int merge_id1, int merge_id2, int shape_id) const { const Shape& merge1 = GetShape(merge_id1); const Shape& merge2 = GetShape(merge_id2); const Shape& shape = GetShape(shape_id); for (int cs = 0; cs < shape.size(); ++cs) { int unichar_id = shape[cs].unichar_id; if (!merge1.ContainsUnichar(unichar_id) && !merge2.ContainsUnichar(unichar_id)) return false; // Shape has a unichar that appears in neither merge. } for (int cm1 = 0; cm1 < merge1.size(); ++cm1) { int unichar_id1 = merge1[cm1].unichar_id; if (!shape.ContainsUnichar(unichar_id1)) return false; // Merge has a unichar that is not in shape. } for (int cm2 = 0; cm2 < merge2.size(); ++cm2) { int unichar_id2 = merge2[cm2].unichar_id; if (!shape.ContainsUnichar(unichar_id2)) return false; // Merge has a unichar that is not in shape. } return true; } // Returns true if there is a common unichar between the shapes. bool ShapeTable::CommonUnichars(int shape_id1, int shape_id2) const { const Shape& shape1 = GetShape(shape_id1); const Shape& shape2 = GetShape(shape_id2); for (int c1 = 0; c1 < shape1.size(); ++c1) { int unichar_id1 = shape1[c1].unichar_id; if (shape2.ContainsUnichar(unichar_id1)) return true; } return false; } // Returns true if there is a common font id between the shapes. bool ShapeTable::CommonFont(int shape_id1, int shape_id2) const { const Shape& shape1 = GetShape(shape_id1); const Shape& shape2 = GetShape(shape_id2); for (int c1 = 0; c1 < shape1.size(); ++c1) { const GenericVector<int>& font_list1 = shape1[c1].font_ids; for (int f = 0; f < font_list1.size(); ++f) { if (shape2.ContainsFont(font_list1[f])) return true; } } return false; } // Appends the master shapes from other to this. // If not NULL, shape_map is set to map other shape_ids to this's shape_ids. void ShapeTable::AppendMasterShapes(const ShapeTable& other, GenericVector<int>* shape_map) { if (shape_map != NULL) shape_map->init_to_size(other.NumShapes(), -1); for (int s = 0; s < other.shape_table_.size(); ++s) { if (other.shape_table_[s]->destination_index() < 0) { int index = AddShape(*other.shape_table_[s]); if (shape_map != NULL) (*shape_map)[s] = index; } } } // Returns the number of master shapes remaining after merging. int ShapeTable::NumMasterShapes() const { int num_shapes = 0; for (int s = 0; s < shape_table_.size(); ++s) { if (shape_table_[s]->destination_index() < 0) ++num_shapes; } return num_shapes; } // Adds the unichars of the given shape_id to the vector of results. Any // unichar_id that is already present just has the fonts added to the // font set for that result without adding a new entry in the vector. // NOTE: it is assumed that the results are given to this function in order // of decreasing rating. // The unichar_map vector indicates the index of the results entry containing // each unichar, or -1 if the unichar is not yet included in results. void ShapeTable::AddShapeToResults(const ShapeRating& shape_rating, GenericVector<int>* unichar_map, GenericVector<UnicharRating>* results)const { if (shape_rating.joined) { AddUnicharToResults(UNICHAR_JOINED, shape_rating.rating, unichar_map, results); } if (shape_rating.broken) { AddUnicharToResults(UNICHAR_BROKEN, shape_rating.rating, unichar_map, results); } const Shape& shape = GetShape(shape_rating.shape_id); for (int u = 0; u < shape.size(); ++u) { int result_index = AddUnicharToResults(shape[u].unichar_id, shape_rating.rating, unichar_map, results); for (int f = 0; f < shape[u].font_ids.size(); ++f) { (*results)[result_index].fonts.push_back( ScoredFont(shape[u].font_ids[f], IntCastRounded(shape_rating.rating * MAX_INT16))); } } } // Adds the given unichar_id to the results if needed, updating unichar_map // and returning the index of unichar in results. int ShapeTable::AddUnicharToResults( int unichar_id, float rating, GenericVector<int>* unichar_map, GenericVector<UnicharRating>* results) const { int result_index = unichar_map->get(unichar_id); if (result_index < 0) { UnicharRating result(unichar_id, rating); result_index = results->push_back(result); (*unichar_map)[unichar_id] = result_index; } return result_index; } } // namespace tesseract
<?xml version = '1.0' encoding = 'ISO-8859-1' ?> <asm version="1.0" name="0"> <cp> <constant value="Families2Persons"/> <constant value="links"/> <constant value="NTransientLinkSet;"/> <constant value="col"/> <constant value="J"/> <constant value="main"/> <constant value="A"/> <constant value="OclParametrizedType"/> <constant value="#native"/> <constant value="Collection"/> <constant value="J.setName(S):V"/> <constant value="OclSimpleType"/> <constant value="OclAny"/> <constant value="J.setElementType(J):V"/> <constant value="Member"/> <constant value="Families"/> <constant value="familyName"/> <constant value="__initfamilyName"/> <constant value="J.registerHelperAttribute(SS):V"/> <constant value="TransientLinkSet"/> <constant value="A.__matcher__():V"/> <constant value="A.__exec__():V"/> <constant value="7:16-7:31"/> <constant value="self"/> <constant value="__resolve__"/> <constant value="1"/> <constant value="J.oclIsKindOf(J):B"/> <constant value="18"/> <constant value="NTransientLinkSet;.getLinkBySourceElement(S):QNTransientLink;"/> <constant value="J.oclIsUndefined():B"/> <constant value="15"/> <constant value="NTransientLink;.getTargetFromSource(J):J"/> <constant value="17"/> <constant value="30"/> <constant value="Sequence"/> <constant value="2"/> <constant value="A.__resolve__(J):J"/> <constant value="QJ.including(J):QJ"/> <constant value="QJ.flatten():QJ"/> <constant value="e"/> <constant value="value"/> <constant value="resolveTemp"/> <constant value="S"/> <constant value="NTransientLink;.getNamedTargetFromSource(JS):J"/> <constant value="name"/> <constant value="__matcher__"/> <constant value="A.__matchMember2Male():V"/> <constant value="A.__matchMember2Female():V"/> <constant value="__exec__"/> <constant value="Member2Male"/> <constant value="NTransientLinkSet;.getLinksByRule(S):QNTransientLink;"/> <constant value="A.__applyMember2Male(NTransientLink;):V"/> <constant value="Member2Female"/> <constant value="A.__applyMember2Female(NTransientLink;):V"/> <constant value="MFamilies!Member;"/> <constant value="0"/> <constant value="familyFather"/> <constant value="J.oclIsUndefined():J"/> <constant value="J.not():J"/> <constant value="27"/> <constant value="familyMother"/> <constant value="23"/> <constant value="familySon"/> <constant value="19"/> <constant value="familyDaughter"/> <constant value="lastName"/> <constant value="22"/> <constant value="26"/> <constant value="8:9-8:13"/> <constant value="8:9-8:26"/> <constant value="8:9-8:43"/> <constant value="8:5-8:43"/> <constant value="11:10-11:14"/> <constant value="11:10-11:27"/> <constant value="11:10-11:44"/> <constant value="11:6-11:44"/> <constant value="14:11-14:15"/> <constant value="14:11-14:25"/> <constant value="14:11-14:42"/> <constant value="14:7-14:42"/> <constant value="17:5-17:9"/> <constant value="17:5-17:24"/> <constant value="17:5-17:33"/> <constant value="15:5-15:9"/> <constant value="15:5-15:19"/> <constant value="15:5-15:28"/> <constant value="14:4-18:9"/> <constant value="12:4-12:8"/> <constant value="12:4-12:21"/> <constant value="12:4-12:30"/> <constant value="11:3-19:8"/> <constant value="9:3-9:7"/> <constant value="9:3-9:20"/> <constant value="9:3-9:29"/> <constant value="8:2-20:7"/> <constant value="isFemale"/> <constant value="14"/> <constant value="12"/> <constant value="13"/> <constant value="23:9-23:13"/> <constant value="23:9-23:26"/> <constant value="23:9-23:43"/> <constant value="23:5-23:43"/> <constant value="26:10-26:14"/> <constant value="26:10-26:29"/> <constant value="26:10-26:46"/> <constant value="26:6-26:46"/> <constant value="29:4-29:9"/> <constant value="27:4-27:8"/> <constant value="26:3-30:8"/> <constant value="24:3-24:7"/> <constant value="23:2-31:7"/> <constant value="__matchMember2Male"/> <constant value="IN"/> <constant value="MMOF!Classifier;.allInstancesFrom(S):QJ"/> <constant value="J.isFemale():J"/> <constant value="B.not():B"/> <constant value="32"/> <constant value="TransientLink"/> <constant value="NTransientLink;.setRule(MATL!Rule;):V"/> <constant value="s"/> <constant value="NTransientLink;.addSourceElement(SJ):V"/> <constant value="t"/> <constant value="Male"/> <constant value="Persons"/> <constant value="NTransientLink;.addTargetElement(SJ):V"/> <constant value="NTransientLinkSet;.addLink2(NTransientLink;B):V"/> <constant value="35:28-35:29"/> <constant value="35:28-35:40"/> <constant value="35:24-35:40"/> <constant value="37:7-37:19"/> <constant value="37:3-39:4"/> <constant value="__applyMember2Male"/> <constant value="NTransientLink;"/> <constant value="NTransientLink;.getSourceElement(S):J"/> <constant value="NTransientLink;.getTargetElement(S):J"/> <constant value="3"/> <constant value="firstName"/> <constant value=" "/> <constant value="J.+(J):J"/> <constant value="fullName"/> <constant value="38:16-38:17"/> <constant value="38:16-38:27"/> <constant value="38:30-38:33"/> <constant value="38:16-38:33"/> <constant value="38:36-38:37"/> <constant value="38:36-38:48"/> <constant value="38:16-38:48"/> <constant value="38:4-38:48"/> <constant value="link"/> <constant value="__matchMember2Female"/> <constant value="31"/> <constant value="Female"/> <constant value="44:24-44:25"/> <constant value="44:24-44:36"/> <constant value="46:7-46:21"/> <constant value="46:3-48:4"/> <constant value="__applyMember2Female"/> <constant value="47:16-47:17"/> <constant value="47:16-47:27"/> <constant value="47:30-47:33"/> <constant value="47:16-47:33"/> <constant value="47:36-47:37"/> <constant value="47:36-47:48"/> <constant value="47:16-47:48"/> <constant value="47:4-47:48"/> </cp> <field name="1" type="2"/> <field name="3" type="4"/> <operation name="5"> <context type="6"/> <parameters> </parameters> <code> <getasm/> <push arg="7"/> <push arg="8"/> <new/> <dup/> <push arg="9"/> <call arg="10"/> <dup/> <push arg="11"/> <push arg="8"/> <new/> <dup/> <push arg="12"/> <call arg="10"/> <call arg="13"/> <set arg="3"/> <push arg="14"/> <push arg="15"/> <findme/> <push arg="16"/> <push arg="17"/> <call arg="18"/> <getasm/> <push arg="19"/> <push arg="8"/> <new/> <set arg="1"/> <getasm/> <call arg="20"/> <getasm/> <call arg="21"/> </code> <linenumbertable> <lne id="22" begin="16" end="18"/> </linenumbertable> <localvariabletable> <lve slot="0" name="23" begin="0" end="30"/> </localvariabletable> </operation> <operation name="24"> <context type="6"/> <parameters> <parameter name="25" type="4"/> </parameters> <code> <load arg="25"/> <getasm/> <get arg="3"/> <call arg="26"/> <if arg="27"/> <getasm/> <get arg="1"/> <load arg="25"/> <call arg="28"/> <dup/> <call arg="29"/> <if arg="30"/> <load arg="25"/> <call arg="31"/> <goto arg="32"/> <pop/> <load arg="25"/> <goto arg="33"/> <push arg="34"/> <push arg="8"/> <new/> <load arg="25"/> <iterate/> <store arg="35"/> <getasm/> <load arg="35"/> <call arg="36"/> <call arg="37"/> <enditerate/> <call arg="38"/> </code> <linenumbertable> </linenumbertable> <localvariabletable> <lve slot="2" name="39" begin="23" end="27"/> <lve slot="0" name="23" begin="0" end="29"/> <lve slot="1" name="40" begin="0" end="29"/> </localvariabletable> </operation> <operation name="41"> <context type="6"/> <parameters> <parameter name="25" type="4"/> <parameter name="35" type="42"/> </parameters> <code> <getasm/> <get arg="1"/> <load arg="25"/> <call arg="28"/> <load arg="25"/> <load arg="35"/> <call arg="43"/> </code> <linenumbertable> </linenumbertable> <localvariabletable> <lve slot="0" name="23" begin="0" end="6"/> <lve slot="1" name="40" begin="0" end="6"/> <lve slot="2" name="44" begin="0" end="6"/> </localvariabletable> </operation> <operation name="45"> <context type="6"/> <parameters> </parameters> <code> <getasm/> <call arg="46"/> <getasm/> <call arg="47"/> </code> <linenumbertable> </linenumbertable> <localvariabletable> <lve slot="0" name="23" begin="0" end="3"/> </localvariabletable> </operation> <operation name="48"> <context type="6"/> <parameters> </parameters> <code> <getasm/> <get arg="1"/> <push arg="49"/> <call arg="50"/> <iterate/> <store arg="25"/> <getasm/> <load arg="25"/> <call arg="51"/> <enditerate/> <getasm/> <get arg="1"/> <push arg="52"/> <call arg="50"/> <iterate/> <store arg="25"/> <getasm/> <load arg="25"/> <call arg="53"/> <enditerate/> </code> <linenumbertable> </linenumbertable> <localvariabletable> <lve slot="1" name="39" begin="5" end="8"/> <lve slot="1" name="39" begin="15" end="18"/> <lve slot="0" name="23" begin="0" end="19"/> </localvariabletable> </operation> <operation name="17"> <context type="54"/> <parameters> </parameters> <code> <load arg="55"/> <get arg="56"/> <call arg="57"/> <call arg="58"/> <if arg="59"/> <load arg="55"/> <get arg="60"/> <call arg="57"/> <call arg="58"/> <if arg="61"/> <load arg="55"/> <get arg="62"/> <call arg="57"/> <call arg="58"/> <if arg="63"/> <load arg="55"/> <get arg="64"/> <get arg="65"/> <goto arg="66"/> <load arg="55"/> <get arg="62"/> <get arg="65"/> <goto arg="67"/> <load arg="55"/> <get arg="60"/> <get arg="65"/> <goto arg="33"/> <load arg="55"/> <get arg="56"/> <get arg="65"/> </code> <linenumbertable> <lne id="68" begin="0" end="0"/> <lne id="69" begin="0" end="1"/> <lne id="70" begin="0" end="2"/> <lne id="71" begin="0" end="3"/> <lne id="72" begin="5" end="5"/> <lne id="73" begin="5" end="6"/> <lne id="74" begin="5" end="7"/> <lne id="75" begin="5" end="8"/> <lne id="76" begin="10" end="10"/> <lne id="77" begin="10" end="11"/> <lne id="78" begin="10" end="12"/> <lne id="79" begin="10" end="13"/> <lne id="80" begin="15" end="15"/> <lne id="81" begin="15" end="16"/> <lne id="82" begin="15" end="17"/> <lne id="83" begin="19" end="19"/> <lne id="84" begin="19" end="20"/> <lne id="85" begin="19" end="21"/> <lne id="86" begin="10" end="21"/> <lne id="87" begin="23" end="23"/> <lne id="88" begin="23" end="24"/> <lne id="89" begin="23" end="25"/> <lne id="90" begin="5" end="25"/> <lne id="91" begin="27" end="27"/> <lne id="92" begin="27" end="28"/> <lne id="93" begin="27" end="29"/> <lne id="94" begin="0" end="29"/> </linenumbertable> <localvariabletable> <lve slot="0" name="23" begin="0" end="29"/> </localvariabletable> </operation> <operation name="95"> <context type="54"/> <parameters> </parameters> <code> <load arg="55"/> <get arg="60"/> <call arg="57"/> <call arg="58"/> <if arg="96"/> <load arg="55"/> <get arg="64"/> <call arg="57"/> <call arg="58"/> <if arg="97"/> <pushf/> <goto arg="98"/> <pusht/> <goto arg="30"/> <pusht/> </code> <linenumbertable> <lne id="99" begin="0" end="0"/> <lne id="100" begin="0" end="1"/> <lne id="101" begin="0" end="2"/> <lne id="102" begin="0" end="3"/> <lne id="103" begin="5" end="5"/> <lne id="104" begin="5" end="6"/> <lne id="105" begin="5" end="7"/> <lne id="106" begin="5" end="8"/> <lne id="107" begin="10" end="10"/> <lne id="108" begin="12" end="12"/> <lne id="109" begin="5" end="12"/> <lne id="110" begin="14" end="14"/> <lne id="111" begin="0" end="14"/> </linenumbertable> <localvariabletable> <lve slot="0" name="23" begin="0" end="14"/> </localvariabletable> </operation> <operation name="112"> <context type="6"/> <parameters> </parameters> <code> <push arg="14"/> <push arg="15"/> <findme/> <push arg="113"/> <call arg="114"/> <iterate/> <store arg="25"/> <load arg="25"/> <call arg="115"/> <call arg="58"/> <call arg="116"/> <if arg="117"/> <getasm/> <get arg="1"/> <push arg="118"/> <push arg="8"/> <new/> <dup/> <push arg="49"/> <call arg="119"/> <dup/> <push arg="120"/> <load arg="25"/> <call arg="121"/> <dup/> <push arg="122"/> <push arg="123"/> <push arg="124"/> <new/> <call arg="125"/> <pusht/> <call arg="126"/> <enditerate/> </code> <linenumbertable> <lne id="127" begin="7" end="7"/> <lne id="128" begin="7" end="8"/> <lne id="129" begin="7" end="9"/> <lne id="130" begin="26" end="28"/> <lne id="131" begin="24" end="29"/> </linenumbertable> <localvariabletable> <lve slot="1" name="120" begin="6" end="31"/> <lve slot="0" name="23" begin="0" end="32"/> </localvariabletable> </operation> <operation name="132"> <context type="6"/> <parameters> <parameter name="25" type="133"/> </parameters> <code> <load arg="25"/> <push arg="120"/> <call arg="134"/> <store arg="35"/> <load arg="25"/> <push arg="122"/> <call arg="135"/> <store arg="136"/> <load arg="136"/> <dup/> <getasm/> <load arg="35"/> <get arg="137"/> <push arg="138"/> <call arg="139"/> <load arg="35"/> <get arg="16"/> <call arg="139"/> <call arg="36"/> <set arg="140"/> <pop/> </code> <linenumbertable> <lne id="141" begin="11" end="11"/> <lne id="142" begin="11" end="12"/> <lne id="143" begin="13" end="13"/> <lne id="144" begin="11" end="14"/> <lne id="145" begin="15" end="15"/> <lne id="146" begin="15" end="16"/> <lne id="147" begin="11" end="17"/> <lne id="148" begin="9" end="19"/> <lne id="131" begin="8" end="20"/> </linenumbertable> <localvariabletable> <lve slot="3" name="122" begin="7" end="20"/> <lve slot="2" name="120" begin="3" end="20"/> <lve slot="0" name="23" begin="0" end="20"/> <lve slot="1" name="149" begin="0" end="20"/> </localvariabletable> </operation> <operation name="150"> <context type="6"/> <parameters> </parameters> <code> <push arg="14"/> <push arg="15"/> <findme/> <push arg="113"/> <call arg="114"/> <iterate/> <store arg="25"/> <load arg="25"/> <call arg="115"/> <call arg="116"/> <if arg="151"/> <getasm/> <get arg="1"/> <push arg="118"/> <push arg="8"/> <new/> <dup/> <push arg="52"/> <call arg="119"/> <dup/> <push arg="120"/> <load arg="25"/> <call arg="121"/> <dup/> <push arg="122"/> <push arg="152"/> <push arg="124"/> <new/> <call arg="125"/> <pusht/> <call arg="126"/> <enditerate/> </code> <linenumbertable> <lne id="153" begin="7" end="7"/> <lne id="154" begin="7" end="8"/> <lne id="155" begin="25" end="27"/> <lne id="156" begin="23" end="28"/> </linenumbertable> <localvariabletable> <lve slot="1" name="120" begin="6" end="30"/> <lve slot="0" name="23" begin="0" end="31"/> </localvariabletable> </operation> <operation name="157"> <context type="6"/> <parameters> <parameter name="25" type="133"/> </parameters> <code> <load arg="25"/> <push arg="120"/> <call arg="134"/> <store arg="35"/> <load arg="25"/> <push arg="122"/> <call arg="135"/> <store arg="136"/> <load arg="136"/> <dup/> <getasm/> <load arg="35"/> <get arg="137"/> <push arg="138"/> <call arg="139"/> <load arg="35"/> <get arg="16"/> <call arg="139"/> <call arg="36"/> <set arg="140"/> <pop/> </code> <linenumbertable> <lne id="158" begin="11" end="11"/> <lne id="159" begin="11" end="12"/> <lne id="160" begin="13" end="13"/> <lne id="161" begin="11" end="14"/> <lne id="162" begin="15" end="15"/> <lne id="163" begin="15" end="16"/> <lne id="164" begin="11" end="17"/> <lne id="165" begin="9" end="19"/> <lne id="156" begin="8" end="20"/> </linenumbertable> <localvariabletable> <lve slot="3" name="122" begin="7" end="20"/> <lve slot="2" name="120" begin="3" end="20"/> <lve slot="0" name="23" begin="0" end="20"/> <lve slot="1" name="149" begin="0" end="20"/> </localvariabletable> </operation> </asm>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright(c) 2011-2019 Intel Corporation All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: ; * Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; * Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in ; the documentation and/or other materials provided with the ; distribution. ; * Neither the name of Intel Corporation nor the names of its ; contributors may be used to endorse or promote products derived ; from this software without specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Function API: ; uint64_t crc64_iso_refl_by16_10( ; uint64_t init_crc, //initial CRC value, 64 bits ; const unsigned char *buf, //buffer pointer to calculate CRC on ; uint64_t len //buffer length in bytes (64-bit data) ; ); ; %include "reg_sizes.asm" %ifndef FUNCTION_NAME %define FUNCTION_NAME crc64_iso_refl_by16_10 %endif %if (AS_FEATURE_LEVEL) >= 10 %define fetch_dist 1024 [bits 64] default rel section .text %ifidn __OUTPUT_FORMAT__, win64 %xdefine arg1 rcx %xdefine arg2 rdx %xdefine arg3 r8 %else %xdefine arg1 rdi %xdefine arg2 rsi %xdefine arg3 rdx %endif %define TMP 16*0 %ifidn __OUTPUT_FORMAT__, win64 %define XMM_SAVE 16*2 %define VARIABLE_OFFSET 16*12+8 %else %define VARIABLE_OFFSET 16*2+8 %endif align 16 mk_global FUNCTION_NAME, function FUNCTION_NAME: not arg1 sub rsp, VARIABLE_OFFSET %ifidn __OUTPUT_FORMAT__, win64 ; push the xmm registers into the stack to maintain vmovdqa [rsp + XMM_SAVE + 16*0], xmm6 vmovdqa [rsp + XMM_SAVE + 16*1], xmm7 vmovdqa [rsp + XMM_SAVE + 16*2], xmm8 vmovdqa [rsp + XMM_SAVE + 16*3], xmm9 vmovdqa [rsp + XMM_SAVE + 16*4], xmm10 vmovdqa [rsp + XMM_SAVE + 16*5], xmm11 vmovdqa [rsp + XMM_SAVE + 16*6], xmm12 vmovdqa [rsp + XMM_SAVE + 16*7], xmm13 vmovdqa [rsp + XMM_SAVE + 16*8], xmm14 vmovdqa [rsp + XMM_SAVE + 16*9], xmm15 %endif cmp arg3, 256 jl _less_than_256 ; load the initial crc value vmovq xmm10, arg1 ; initial crc ; receive the initial 128B data, xor the initial crc value vmovdqu8 zmm0, [arg2+16*0] vmovdqu8 zmm4, [arg2+16*4] vpxorq zmm0, zmm10 vbroadcasti32x4 zmm10, [rk3] ;zmm10 has rk3 and rk4 ;imm value of pclmulqdq instruction will determine which constant to use sub arg3, 256 cmp arg3, 256 jl _fold_128_B_loop vmovdqu8 zmm7, [arg2+16*8] vmovdqu8 zmm8, [arg2+16*12] vbroadcasti32x4 zmm16, [rk_1] ;zmm16 has rk-1 and rk-2 sub arg3, 256 _fold_256_B_loop: add arg2, 256 vmovdqu8 zmm3, [arg2+16*0] vpclmulqdq zmm1, zmm0, zmm16, 0x10 vpclmulqdq zmm2, zmm0, zmm16, 0x01 vpxorq zmm0, zmm1, zmm2 vpxorq zmm0, zmm0, zmm3 vmovdqu8 zmm9, [arg2+16*4] vpclmulqdq zmm5, zmm4, zmm16, 0x10 vpclmulqdq zmm6, zmm4, zmm16, 0x01 vpxorq zmm4, zmm5, zmm6 vpxorq zmm4, zmm4, zmm9 vmovdqu8 zmm11, [arg2+16*8] vpclmulqdq zmm12, zmm7, zmm16, 0x10 vpclmulqdq zmm13, zmm7, zmm16, 0x01 vpxorq zmm7, zmm12, zmm13 vpxorq zmm7, zmm7, zmm11 vmovdqu8 zmm17, [arg2+16*12] vpclmulqdq zmm14, zmm8, zmm16, 0x10 vpclmulqdq zmm15, zmm8, zmm16, 0x01 vpxorq zmm8, zmm14, zmm15 vpxorq zmm8, zmm8, zmm17 sub arg3, 256 jge _fold_256_B_loop ;; Fold 256 into 128 add arg2, 256 vpclmulqdq zmm1, zmm0, zmm10, 0x01 vpclmulqdq zmm2, zmm0, zmm10, 0x10 vpternlogq zmm7, zmm1, zmm2, 0x96 ; xor ABC vpclmulqdq zmm5, zmm4, zmm10, 0x01 vpclmulqdq zmm6, zmm4, zmm10, 0x10 vpternlogq zmm8, zmm5, zmm6, 0x96 ; xor ABC vmovdqa32 zmm0, zmm7 vmovdqa32 zmm4, zmm8 add arg3, 128 jmp _fold_128_B_register ; fold 128B at a time. This section of the code folds 2 zmm registers in parallel _fold_128_B_loop: add arg2, 128 ; update the buffer pointer vmovdqu8 zmm8, [arg2+16*0] vpclmulqdq zmm1, zmm0, zmm10, 0x10 vpclmulqdq zmm2, zmm0, zmm10, 0x01 vpxorq zmm0, zmm1, zmm2 vpxorq zmm0, zmm0, zmm8 vmovdqu8 zmm9, [arg2+16*4] vpclmulqdq zmm5, zmm4, zmm10, 0x10 vpclmulqdq zmm6, zmm4, zmm10, 0x01 vpxorq zmm4, zmm5, zmm6 vpxorq zmm4, zmm4, zmm9 sub arg3, 128 jge _fold_128_B_loop ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; add arg2, 128 ; at this point, the buffer pointer is pointing at the last y Bytes of the buffer, where 0 <= y < 128 ; the 128B of folded data is in 2 zmm registers: zmm0, zmm4 _fold_128_B_register: ; fold the 8 128b parts into 1 xmm register with different constants vmovdqu8 zmm16, [rk9] ; multiply by rk9-rk16 vmovdqu8 zmm11, [rk17] ; multiply by rk17-rk20, rk1,rk2, 0,0 vpclmulqdq zmm1, zmm0, zmm16, 0x01 vpclmulqdq zmm2, zmm0, zmm16, 0x10 vextracti64x2 xmm7, zmm4, 3 ; save last that has no multiplicand vpclmulqdq zmm5, zmm4, zmm11, 0x01 vpclmulqdq zmm6, zmm4, zmm11, 0x10 vmovdqa xmm10, [rk1] ; Needed later in reduction loop vpternlogq zmm1, zmm2, zmm5, 0x96 ; xor ABC vpternlogq zmm1, zmm6, zmm7, 0x96 ; xor ABC vshufi64x2 zmm8, zmm1, zmm1, 0x4e ; Swap 1,0,3,2 - 01 00 11 10 vpxorq ymm8, ymm8, ymm1 vextracti64x2 xmm5, ymm8, 1 vpxorq xmm7, xmm5, xmm8 ; instead of 128, we add 128-16 to the loop counter to save 1 instruction from the loop ; instead of a cmp instruction, we use the negative flag with the jl instruction add arg3, 128-16 jl _final_reduction_for_128 ; now we have 16+y bytes left to reduce. 16 Bytes is in register xmm7 and the rest is in memory ; we can fold 16 bytes at a time if y>=16 ; continue folding 16B at a time _16B_reduction_loop: vmovdqa xmm8, xmm7 vpclmulqdq xmm7, xmm10, 0x1 vpclmulqdq xmm8, xmm10, 0x10 vpxor xmm7, xmm8 vmovdqu xmm0, [arg2] vpxor xmm7, xmm0 add arg2, 16 sub arg3, 16 ; instead of a cmp instruction, we utilize the flags with the jge instruction ; equivalent of: cmp arg3, 16-16 ; check if there is any more 16B in the buffer to be able to fold jge _16B_reduction_loop ;now we have 16+z bytes left to reduce, where 0<= z < 16. ;first, we reduce the data in the xmm7 register _final_reduction_for_128: add arg3, 16 je _128_done ; here we are getting data that is less than 16 bytes. ; since we know that there was data before the pointer, we can offset ; the input pointer before the actual point, to receive exactly 16 bytes. ; after that the registers need to be adjusted. _get_last_two_xmms: vmovdqa xmm2, xmm7 vmovdqu xmm1, [arg2 - 16 + arg3] ; get rid of the extra data that was loaded before ; load the shift constant lea rax, [pshufb_shf_table] add rax, arg3 vmovdqu xmm0, [rax] vpshufb xmm7, xmm0 vpxor xmm0, [mask3] vpshufb xmm2, xmm0 vpblendvb xmm2, xmm2, xmm1, xmm0 ;;;;;;;;;; vmovdqa xmm8, xmm7 vpclmulqdq xmm7, xmm10, 0x1 vpclmulqdq xmm8, xmm10, 0x10 vpxor xmm7, xmm8 vpxor xmm7, xmm2 _128_done: ; compute crc of a 128-bit value vmovdqa xmm10, [rk5] vmovdqa xmm0, xmm7 ;64b fold vpclmulqdq xmm7, xmm10, 0 vpsrldq xmm0, 8 vpxor xmm7, xmm0 ;barrett reduction _barrett: vmovdqa xmm1, xmm7 vmovdqa xmm10, [rk7] vpclmulqdq xmm7, xmm10, 0 vmovdqa xmm2, xmm7 vpclmulqdq xmm7, xmm10, 0x10 vpslldq xmm2, 8 vpxor xmm7, xmm2 vpxor xmm7, xmm1 vpextrq rax, xmm7, 1 _cleanup: not rax %ifidn __OUTPUT_FORMAT__, win64 vmovdqa xmm6, [rsp + XMM_SAVE + 16*0] vmovdqa xmm7, [rsp + XMM_SAVE + 16*1] vmovdqa xmm8, [rsp + XMM_SAVE + 16*2] vmovdqa xmm9, [rsp + XMM_SAVE + 16*3] vmovdqa xmm10, [rsp + XMM_SAVE + 16*4] vmovdqa xmm11, [rsp + XMM_SAVE + 16*5] vmovdqa xmm12, [rsp + XMM_SAVE + 16*6] vmovdqa xmm13, [rsp + XMM_SAVE + 16*7] vmovdqa xmm14, [rsp + XMM_SAVE + 16*8] vmovdqa xmm15, [rsp + XMM_SAVE + 16*9] %endif add rsp, VARIABLE_OFFSET ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 _less_than_256: ; check if there is enough buffer to be able to fold 16B at a time cmp arg3, 32 jl _less_than_32 ; if there is, load the constants vmovdqa xmm10, [rk1] ; rk1 and rk2 in xmm10 vmovq xmm0, arg1 ; get the initial crc value vmovdqu xmm7, [arg2] ; load the plaintext vpxor xmm7, xmm0 ; update the buffer pointer add arg2, 16 ; update the counter. subtract 32 instead of 16 to save one instruction from the loop sub arg3, 32 jmp _16B_reduction_loop align 16 _less_than_32: ; mov initial crc to the return value. this is necessary for zero-length buffers. mov rax, arg1 test arg3, arg3 je _cleanup vmovq xmm0, arg1 ; get the initial crc value cmp arg3, 16 je _exact_16_left jl _less_than_16_left vmovdqu xmm7, [arg2] ; load the plaintext vpxor xmm7, xmm0 ; xor the initial crc value add arg2, 16 sub arg3, 16 vmovdqa xmm10, [rk1] ; rk1 and rk2 in xmm10 jmp _get_last_two_xmms align 16 _less_than_16_left: ; use stack space to load data less than 16 bytes, zero-out the 16B in memory first. vpxor xmm1, xmm1 mov r11, rsp vmovdqa [r11], xmm1 ; backup the counter value mov r9, arg3 cmp arg3, 8 jl _less_than_8_left ; load 8 Bytes mov rax, [arg2] mov [r11], rax add r11, 8 sub arg3, 8 add arg2, 8 _less_than_8_left: cmp arg3, 4 jl _less_than_4_left ; load 4 Bytes mov eax, [arg2] mov [r11], eax add r11, 4 sub arg3, 4 add arg2, 4 _less_than_4_left: cmp arg3, 2 jl _less_than_2_left ; load 2 Bytes mov ax, [arg2] mov [r11], ax add r11, 2 sub arg3, 2 add arg2, 2 _less_than_2_left: cmp arg3, 1 jl _zero_left ; load 1 Byte mov al, [arg2] mov [r11], al _zero_left: vmovdqa xmm7, [rsp] vpxor xmm7, xmm0 ; xor the initial crc value lea rax,[pshufb_shf_table] cmp r9, 8 jl _end_1to7 _end_8to15: vmovdqu xmm0, [rax + r9] vpshufb xmm7,xmm0 jmp _128_done _end_1to7: ; Left shift (8-length) bytes in XMM vmovdqu xmm0, [rax + r9 + 8] vpshufb xmm7,xmm0 jmp _barrett align 16 _exact_16_left: vmovdqu xmm7, [arg2] vpxor xmm7, xmm0 ; xor the initial crc value jmp _128_done section .data align 32 %ifndef USE_CONSTS ; precomputed constants rk_1: dq 0x45000000b0000000 rk_2: dq 0x6b700000f5000000 rk1: dq 0xf500000000000001 rk2: dq 0x6b70000000000001 rk3: dq 0xb001000000010000 rk4: dq 0xf501b0000001b000 rk5: dq 0xf500000000000001 rk6: dq 0x0000000000000000 rk7: dq 0xb000000000000001 rk8: dq 0xb000000000000000 rk9: dq 0xe014514514501501 rk10: dq 0x771db6db6db71c71 rk11: dq 0xa101101101110001 rk12: dq 0x1ab1ab1ab1aab001 rk13: dq 0xf445014445000001 rk14: dq 0x6aab71daab700001 rk15: dq 0xb100010100000001 rk16: dq 0x01b001b1b0000001 rk17: dq 0xe145150000000001 rk18: dq 0x76db6c7000000001 rk19: dq 0xa011000000000001 rk20: dq 0x1b1ab00000000001 rk_1b: dq 0xf500000000000001 rk_2b: dq 0x6b70000000000001 dq 0x0000000000000000 dq 0x0000000000000000 %else INCLUDE_CONSTS %endif pshufb_shf_table: ; use these values for shift constants for the pshufb instruction ; different alignments result in values as shown: ; dq 0x8887868584838281, 0x008f8e8d8c8b8a89 ; shl 15 (16-1) / shr1 ; dq 0x8988878685848382, 0x01008f8e8d8c8b8a ; shl 14 (16-3) / shr2 ; dq 0x8a89888786858483, 0x0201008f8e8d8c8b ; shl 13 (16-4) / shr3 ; dq 0x8b8a898887868584, 0x030201008f8e8d8c ; shl 12 (16-4) / shr4 ; dq 0x8c8b8a8988878685, 0x04030201008f8e8d ; shl 11 (16-5) / shr5 ; dq 0x8d8c8b8a89888786, 0x0504030201008f8e ; shl 10 (16-6) / shr6 ; dq 0x8e8d8c8b8a898887, 0x060504030201008f ; shl 9 (16-7) / shr7 ; dq 0x8f8e8d8c8b8a8988, 0x0706050403020100 ; shl 8 (16-8) / shr8 ; dq 0x008f8e8d8c8b8a89, 0x0807060504030201 ; shl 7 (16-9) / shr9 ; dq 0x01008f8e8d8c8b8a, 0x0908070605040302 ; shl 6 (16-10) / shr10 ; dq 0x0201008f8e8d8c8b, 0x0a09080706050403 ; shl 5 (16-11) / shr11 ; dq 0x030201008f8e8d8c, 0x0b0a090807060504 ; shl 4 (16-12) / shr12 ; dq 0x04030201008f8e8d, 0x0c0b0a0908070605 ; shl 3 (16-13) / shr13 ; dq 0x0504030201008f8e, 0x0d0c0b0a09080706 ; shl 2 (16-14) / shr14 ; dq 0x060504030201008f, 0x0e0d0c0b0a090807 ; shl 1 (16-15) / shr15 dq 0x8786858483828100, 0x8f8e8d8c8b8a8988 dq 0x0706050403020100, 0x000e0d0c0b0a0908 mask: dq 0xFFFFFFFFFFFFFFFF, 0x0000000000000000 mask2: dq 0xFFFFFFFF00000000, 0xFFFFFFFFFFFFFFFF mask3: dq 0x8080808080808080, 0x8080808080808080 %else ; Assembler doesn't understand these opcodes. Add empty symbol for windows. %ifidn __OUTPUT_FORMAT__, win64 global no_ %+ FUNCTION_NAME no_ %+ FUNCTION_NAME %+ : %endif %endif ; (AS_FEATURE_LEVEL) >= 10
; Z88 Small C+ Run Time Library ; Long functions ; XLIB l_long_or ; "or" primary and secondary into dehl ; dehl = primary ; stack = secondary, ret .l_long_or pop ix pop bc ld a,c or l ld l,a ld a,b or h ld h,a pop bc ld a,c or e ld e,a ld a,b or d ld d,a jp (ix) ;.l_long_or ; ld a,d ; exx ;primary; ; pop bc ; pop hl ; pop de ; push bc ; or d ; ld d,a ; ld a,e ; exx ;2nd ; or e ; exx ;1st ; ld e,a ; ld a,h ; exx ;2nd ; or h ; exx ;1st ; ld h,a ; ld a,l ; exx ;2nd ; or l ; exx ;1st ; ld l,a ; ret
opt c,ct ******************************************************************************** * Game Engine (TO8 Thomson) - Benoit Rousseau 2020-2021 * ------------------------------------------------------------------------------ * * ******************************************************************************** INCLUDE "./GameMode/LostWoods/LostWoodsRamData.equ" INCLUDE "./Engine/Constants.asm" INCLUDE "./Engine/Macros.asm" org $6100 jsr LoadAct jsr YM2413_DrumModeOn jsr IrqSet50Hz ldx #Smps_Zelda jsr PlayMusic * ============================================================================== * Intro * ============================================================================== IntroMainLoop jsr WaitVBL jsr UpdatePalette jsr ReadJoypads ldb Fire_Press bitb #c1_button_A_mask bne InitLevelMainLoop jsr RunObjects jsr CheckSpritesRefresh jsr EraseSprites jsr UnsetDisplayPriority jsr DrawSprites bra IntroMainLoop InitLevelMainLoop ldd #Black_palette std Cur_palette clr Refresh_palette jsr WaitVBL jsr UpdatePalette ldb #$02 * load page 2 stb $E7E5 * in data space ($A000-$DFFF) ldx #$EEEE * set Background solid color jsr ClearDataMem lda $E7DD * set border color anda #$F0 adda #$0E * color ref sta $E7DD anda #$0F adda #$80 sta glb_screen_border_color+1 * maj WaitVBL jsr WaitVBL ldb #$03 * load page 3 stb $E7E5 * data space ($A000-$DFFF) ldx #$EEEE * set Background solid color jsr ClearDataMem ; TODO put this as two routines in engine, one for cleaning all objects, another for cleaning Display priority data ldu #Object_RAM @a jsr ClearObj leau object_size,u cmpu #Object_RAM_End bne @a lda #ObjID_Link sta LinkData ldu #Tbl_Priority_First_Entry_0 ldd #0 @b std ,u++ cmpu #DPS_buffer_end bne @b ldd #Lst_Priority_Unset_0+2 std Lst_Priority_Unset_0 ldd #Lst_Priority_Unset_1+2 std Lst_Priority_Unset_1 ldd #Pal_LostWoods1 std Cur_palette clr Refresh_palette _RunObjectRoutine ObjID_Tilemap,glb_current_submap * ============================================================================== * Main Loop * ============================================================================== LevelMainLoop jsr WaitVBL jsr UpdatePalette jsr ReadJoypads jsr AutoScroll jsr RunObjects _RunObjectRoutine ObjID_Tilemap,glb_current_submap jsr CheckSpritesRefresh jsr EraseSprites jsr UnsetDisplayPriority jsr DrawTilemap jsr DrawSprites bra LevelMainLoop * ============================================================================== * Game Mode RAM variables * ============================================================================== INCLUDE "./GameMode/LostWoods/LostWoodsRamData.asm" * ============================================================================== * Routines * ============================================================================== INCLUDE "./Engine/Ram/BankSwitch.asm" INCLUDE "./Engine/Graphics/WaitVBL.asm" INCLUDE "./Engine/Graphics/AnimateSprite.asm" INCLUDE "./Engine/Graphics/DisplaySprite.asm" INCLUDE "./Engine/Graphics/CheckSpritesRefresh.asm" INCLUDE "./Engine/Graphics/EraseSprites.asm" INCLUDE "./Engine/Graphics/UnsetDisplayPriority.asm" INCLUDE "./Engine/Graphics/DrawSpritesExtEnc.asm" INCLUDE "./Engine/Graphics/BgBufferAlloc.asm" INCLUDE "./Engine/Joypad/ReadJoypads.asm" INCLUDE "./Engine/Irq/IrqSmpsJoypad.asm" INCLUDE "./Engine/Sound/Smps.asm" INCLUDE "./Engine/ObjectManagement/RunObjects.asm" INCLUDE "./Engine/ObjectManagement/DeleteObject.asm" INCLUDE "./Engine/ObjectManagement/ClearObj.asm" INCLUDE "./Engine/ObjectManagement/RunPgSubRoutine.asm" INCLUDE "./Engine/ObjectManagement/SingleObjLoad.asm" INCLUDE "./Engine/Ram/ClearDataMemory.asm" INCLUDE "./Engine/Palette/UpdatePalette.asm" INCLUDE "./Engine/Graphics/Camera/AutoScroll.asm" INCLUDE "./Engine/Graphics/Tilemap/Tilemap.asm" INCLUDE "./Engine/Graphics/GetImgIdA.asm" INCLUDE "./Engine/Graphics/Codec/DecRLE00.asm" zx0_decompress rts
; int asprintf(char **s, const char *fmt, ...) ; 05.2008 aralbrec PUBLIC asprintf EXTERN vasprintf_callee, stdio_varg, stdio_nextarg EXTERN ASMDISP_VASPRINTF_CALLEE .asprintf call stdio_varg push de ; stack = char **s call stdio_nextarg ; de = char *fmt ld c,l ld b,h ; bc = top of parameter list exx pop hl ; char **s ld de,0 exx jp vasprintf_callee + ASMDISP_VASPRINTF_CALLEE
; A135450: a(n) = 3*a(n-1) + 4*a(n-2) - a(n-3) + 3*a(n-4) + 4*a(n-5). ; 0,0,0,1,4,16,63,252,1008,4033,16132,64528,258111,1032444,4129776,16519105,66076420,264305680,1057222719,4228890876,16915563504,67662254017,270649016068,1082596064272,4330384257087,17321537028348,69286148113392,277144592453569,1108578369814276,4434313479257104,17737253917028415,70949015668113660,283796062672454640,1135184250689818561,4540737002759274244,18162948011037096976,72651792044148387903,290607168176593551612,1162428672706374206448,4649714690825496825793,18598858763301987303172 mov $2,$0 mov $0,64 mov $1,4 pow $1,$2 add $1,21 lpb $0 mov $3,1 add $3,$0 mov $0,1 add $1,$3 div $1,$3 mul $1,2 mul $1,$3 lpe sub $1,130 div $1,130 mov $0,$1
db DEX_ELECTRODE ; pokedex id db 60 ; base hp db 50 ; base attack db 70 ; base defense db 140 ; base speed db 80 ; base special db ELECTRIC ; species type 1 db ELECTRIC ; species type 2 db 58 ; catch rate db 150 ; base exp yield INCBIN "pic/ymon/electrode.pic",0,1 ; 55, sprite dimensions dw ElectrodePicFront dw ElectrodePicBack ; attacks known at lvl 0 db TACKLE db SCREECH db SONICBOOM db 0 db 0 ; growth rate ; learnset tmlearn 6 tmlearn 9,15 tmlearn 20,24 tmlearn 25,30,31,32 tmlearn 33,34,36,39,40 tmlearn 44,45,47 tmlearn 50,55 db BANK(ElectrodePicFront)
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/css/RuleFeature.h" #include "core/css/CSSSelectorList.h" #include "core/css/RuleSet.h" #include "core/css/StylePropertySet.h" #include "core/css/StyleRule.h" #include "core/css/invalidation/InvalidationSet.h" #include "core/css/parser/CSSParser.h" #include "core/dom/ElementTraversal.h" #include "core/html/HTMLBodyElement.h" #include "core/html/HTMLDocument.h" #include "core/html/HTMLElement.h" #include "core/html/HTMLHtmlElement.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { class RuleFeatureSetTest : public ::testing::Test { public: RuleFeatureSetTest() { } void SetUp() { m_document = HTMLDocument::create(); RefPtrWillBeRawPtr<HTMLHtmlElement> html = HTMLHtmlElement::create(*m_document); html->appendChild(HTMLBodyElement::create(*m_document)); m_document->appendChild(html.release()); m_document->body()->setInnerHTML("<b><i></i></b>", ASSERT_NO_EXCEPTION); } void updateInvalidationSets(const String& selectorText) { CSSSelectorList selectorList = CSSParser::parseSelector(strictCSSParserContext(), selectorText); RefPtrWillBeRawPtr<StyleRule> styleRule = StyleRule::create(std::move(selectorList), MutableStylePropertySet::create(HTMLStandardMode)); RuleData ruleData(styleRule.get(), 0, 0, RuleHasNoSpecialState); m_ruleFeatureSet.updateInvalidationSets(ruleData); } void collectInvalidationSetsForClass(InvalidationLists& invalidationLists, const AtomicString& className) const { Element* element = Traversal<HTMLElement>::firstChild(*Traversal<HTMLElement>::firstChild(*m_document->body())); m_ruleFeatureSet.collectInvalidationSetsForClass(invalidationLists, *element, className); } void collectInvalidationSetsForId(InvalidationLists& invalidationLists, const AtomicString& id) const { Element* element = Traversal<HTMLElement>::firstChild(*Traversal<HTMLElement>::firstChild(*m_document->body())); m_ruleFeatureSet.collectInvalidationSetsForId(invalidationLists, *element, id); } void collectInvalidationSetsForAttribute(InvalidationLists& invalidationLists, const QualifiedName& attributeName) const { Element* element = Traversal<HTMLElement>::firstChild(*Traversal<HTMLElement>::firstChild(*m_document->body())); m_ruleFeatureSet.collectInvalidationSetsForAttribute(invalidationLists, *element, attributeName); } void collectInvalidationSetsForPseudoClass(InvalidationLists& invalidationLists, CSSSelector::PseudoType pseudo) const { Element* element = Traversal<HTMLElement>::firstChild(*Traversal<HTMLElement>::firstChild(*m_document->body())); m_ruleFeatureSet.collectInvalidationSetsForPseudoClass(invalidationLists, *element, pseudo); } const HashSet<AtomicString>& classSet(const InvalidationSet& invalidationSet) { return invalidationSet.classSetForTesting(); } const HashSet<AtomicString>& idSet(const InvalidationSet& invalidationSet) { return invalidationSet.idSetForTesting(); } const HashSet<AtomicString>& tagNameSet(const InvalidationSet& invalidationSet) { return invalidationSet.tagNameSetForTesting(); } const HashSet<AtomicString>& attributeSet(const InvalidationSet& invalidationSet) { return invalidationSet.attributeSetForTesting(); } void expectNoInvalidation(InvalidationSetVector& invalidationSets) { EXPECT_EQ(0u, invalidationSets.size()); } void expectSelfInvalidation(InvalidationSetVector& invalidationSets) { EXPECT_EQ(1u, invalidationSets.size()); EXPECT_TRUE(invalidationSets[0]->invalidatesSelf()); } void expectNoSelfInvalidation(InvalidationSetVector& invalidationSets) { EXPECT_EQ(1u, invalidationSets.size()); EXPECT_FALSE(invalidationSets[0]->invalidatesSelf()); } void expectClassInvalidation(const AtomicString& className, InvalidationSetVector& invalidationSets) { EXPECT_EQ(1u, invalidationSets.size()); HashSet<AtomicString> classes = classSet(*invalidationSets[0]); EXPECT_EQ(1u, classes.size()); EXPECT_TRUE(classes.contains(className)); } void expectSiblingInvalidation(unsigned maxDirectAdjacentSelectors, const AtomicString& siblingName, InvalidationSetVector& invalidationSets) { EXPECT_EQ(1u, invalidationSets.size()); const SiblingInvalidationSet& siblingInvalidationSet = toSiblingInvalidationSet(*invalidationSets[0]); HashSet<AtomicString> classes = classSet(siblingInvalidationSet); EXPECT_EQ(1u, classes.size()); EXPECT_TRUE(classes.contains(siblingName)); EXPECT_EQ(maxDirectAdjacentSelectors, siblingInvalidationSet.maxDirectAdjacentSelectors()); } void expectSiblingDescendantInvalidation(unsigned maxDirectAdjacentSelectors, const AtomicString& siblingName, const AtomicString& descendantName, InvalidationSetVector& invalidationSets) { EXPECT_EQ(1u, invalidationSets.size()); const SiblingInvalidationSet& siblingInvalidationSet = toSiblingInvalidationSet(*invalidationSets[0]); HashSet<AtomicString> classes = classSet(siblingInvalidationSet); EXPECT_EQ(1u, classes.size()); EXPECT_TRUE(classes.contains(siblingName)); EXPECT_EQ(maxDirectAdjacentSelectors, siblingInvalidationSet.maxDirectAdjacentSelectors()); HashSet<AtomicString> descendantClasses = classSet(siblingInvalidationSet.descendants()); EXPECT_EQ(1u, descendantClasses.size()); EXPECT_TRUE(descendantClasses.contains(descendantName)); } void expectClassesInvalidation(const AtomicString& firstClassName, const AtomicString& secondClassName, InvalidationSetVector& invalidationSets) { EXPECT_EQ(1u, invalidationSets.size()); HashSet<AtomicString> classes = classSet(*invalidationSets[0]); EXPECT_EQ(2u, classes.size()); EXPECT_TRUE(classes.contains(firstClassName)); EXPECT_TRUE(classes.contains(secondClassName)); } void expectIdInvalidation(const AtomicString& id, InvalidationSetVector& invalidationSets) { EXPECT_EQ(1u, invalidationSets.size()); HashSet<AtomicString> ids = idSet(*invalidationSets[0]); EXPECT_EQ(1u, ids.size()); EXPECT_TRUE(ids.contains(id)); } void expectTagNameInvalidation(const AtomicString& tagName, InvalidationSetVector& invalidationSets) { EXPECT_EQ(1u, invalidationSets.size()); HashSet<AtomicString> tagNames = tagNameSet(*invalidationSets[0]); EXPECT_EQ(1u, tagNames.size()); EXPECT_TRUE(tagNames.contains(tagName)); } void expectAttributeInvalidation(const AtomicString& attribute, InvalidationSetVector& invalidationSets) { EXPECT_EQ(1u, invalidationSets.size()); HashSet<AtomicString> attributes = attributeSet(*invalidationSets[0]); EXPECT_EQ(1u, attributes.size()); EXPECT_TRUE(attributes.contains(attribute)); } DEFINE_INLINE_TRACE() { #if ENABLE(OILPAN) visitor->trace(m_ruleFeatureSet); visitor->trace(m_document); #endif } private: RuleFeatureSet m_ruleFeatureSet; RefPtrWillBePersistent<Document> m_document; }; TEST_F(RuleFeatureSetTest, interleavedDescendantSibling1) { updateInvalidationSets(".p"); InvalidationLists invalidationLists; collectInvalidationSetsForClass(invalidationLists, "p"); expectSelfInvalidation(invalidationLists.descendants); expectNoInvalidation(invalidationLists.siblings); } TEST_F(RuleFeatureSetTest, interleavedDescendantSibling2) { updateInvalidationSets(".o + .p"); InvalidationLists invalidationLists; collectInvalidationSetsForClass(invalidationLists, "o"); expectNoInvalidation(invalidationLists.descendants); expectSiblingInvalidation(1, "p", invalidationLists.siblings); } TEST_F(RuleFeatureSetTest, interleavedDescendantSibling3) { updateInvalidationSets(".m + .n .o + .p"); InvalidationLists invalidationLists; collectInvalidationSetsForClass(invalidationLists, "n"); expectNoSelfInvalidation(invalidationLists.descendants); expectClassInvalidation("p", invalidationLists.descendants); expectNoInvalidation(invalidationLists.siblings); } TEST_F(RuleFeatureSetTest, interleavedDescendantSibling4) { updateInvalidationSets(".m + .n .o + .p"); InvalidationLists invalidationLists; collectInvalidationSetsForClass(invalidationLists, "m"); expectNoInvalidation(invalidationLists.descendants); expectSiblingDescendantInvalidation(1, "n", "p", invalidationLists.siblings); } TEST_F(RuleFeatureSetTest, interleavedDescendantSibling5) { updateInvalidationSets(".l ~ .m + .n .o + .p"); InvalidationLists invalidationLists; collectInvalidationSetsForClass(invalidationLists, "l"); expectNoInvalidation(invalidationLists.descendants); expectSiblingDescendantInvalidation(UINT_MAX, "n", "p", invalidationLists.siblings); } TEST_F(RuleFeatureSetTest, interleavedDescendantSibling6) { updateInvalidationSets(".k > .l ~ .m + .n .o + .p"); InvalidationLists invalidationLists; collectInvalidationSetsForClass(invalidationLists, "k"); expectClassInvalidation("p", invalidationLists.descendants); expectNoInvalidation(invalidationLists.siblings); } TEST_F(RuleFeatureSetTest, anySibling) { updateInvalidationSets(":-webkit-any(.q, .r) ~ .s .t"); InvalidationLists invalidationLists; collectInvalidationSetsForClass(invalidationLists, "q"); expectNoInvalidation(invalidationLists.descendants); expectSiblingDescendantInvalidation(UINT_MAX, "s", "t", invalidationLists.siblings); } TEST_F(RuleFeatureSetTest, any) { updateInvalidationSets(":-webkit-any(.w, .x)"); InvalidationLists invalidationLists; collectInvalidationSetsForClass(invalidationLists, "w"); expectSelfInvalidation(invalidationLists.descendants); expectNoInvalidation(invalidationLists.siblings); } TEST_F(RuleFeatureSetTest, siblingAny) { updateInvalidationSets(".v ~ :-webkit-any(.w, .x)"); InvalidationLists invalidationLists; collectInvalidationSetsForClass(invalidationLists, "v"); expectNoInvalidation(invalidationLists.descendants); expectClassesInvalidation("w", "x", invalidationLists.siblings); } TEST_F(RuleFeatureSetTest, descendantSiblingAny) { updateInvalidationSets(".u .v ~ :-webkit-any(.w, .x)"); InvalidationLists invalidationLists; collectInvalidationSetsForClass(invalidationLists, "u"); expectClassesInvalidation("w", "x", invalidationLists.descendants); expectNoInvalidation(invalidationLists.siblings); } TEST_F(RuleFeatureSetTest, id) { updateInvalidationSets("#a #b"); InvalidationLists invalidationLists; collectInvalidationSetsForId(invalidationLists, "a"); expectIdInvalidation("b", invalidationLists.descendants); } TEST_F(RuleFeatureSetTest, attribute) { updateInvalidationSets("[c] [d]"); InvalidationLists invalidationLists; collectInvalidationSetsForAttribute(invalidationLists, QualifiedName("", "c", "")); expectAttributeInvalidation("d", invalidationLists.descendants); } TEST_F(RuleFeatureSetTest, pseudoClass) { updateInvalidationSets(":valid"); InvalidationLists invalidationLists; collectInvalidationSetsForPseudoClass(invalidationLists, CSSSelector::PseudoValid); expectSelfInvalidation(invalidationLists.descendants); } TEST_F(RuleFeatureSetTest, tagName) { updateInvalidationSets(":valid e"); InvalidationLists invalidationLists; collectInvalidationSetsForPseudoClass(invalidationLists, CSSSelector::PseudoValid); expectTagNameInvalidation("e", invalidationLists.descendants); } TEST_F(RuleFeatureSetTest, contentPseudo) { updateInvalidationSets(".a ::content .b"); updateInvalidationSets(".a .c"); InvalidationLists invalidationLists; collectInvalidationSetsForClass(invalidationLists, "a"); expectClassInvalidation("c", invalidationLists.descendants); updateInvalidationSets(".a .b"); invalidationLists.descendants.clear(); collectInvalidationSetsForClass(invalidationLists, "a"); expectClassesInvalidation("b", "c", invalidationLists.descendants); } } // namespace blink
; A164660: Numerators of row sums of triangle of rationals A164658/A164659. Definite integral of Chebyshev polynomials of the first kind: Integral_{x=0..1} T(n,x). ; 1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1 trn $0,1 gcd $0,4 sub $0,10 div $0,7 mov $1,$0 mul $1,2 add $1,1
; void *wv_stack_pop(wv_stack_t *s) SECTION code_clib SECTION code_adt_wv_stack PUBLIC wv_stack_pop EXTERN asm_wv_stack_pop defc wv_stack_pop = asm_wv_stack_pop ; SDCC bridge for Classic IF __CLASSIC PUBLIC _wv_stack_pop defc _wv_stack_pop = wv_stack_pop ENDIF
[BITS 64] ;global _start:function global div_r8:function global div_m8:function global div_r16:function global div_m16:function global div_r32:function global div_m32:function global div_r64:function global div_m64:function section .text ;_start: ; call div_m64 ; ; sys_exit(eax) ; mov ebx, eax ; mov eax, 1 ; int 0x80 ;add: ; mov eax, 29 ; add eax, 13 ; ret ;sub: ; mov eax, 55 ; sub eax, 13 ; ret ;mul: ; mov eax, 2 ; mov ebx, 21 ; mul eax ; ret ;imul: ; mov eax, 2 ; imul eax, 21 ; ret ; === [ div arg ] ============================================================== ; ; --- [ 8-bit divisor arg ] ---------------------------------------------------- ; ; AX ; ___________________ => AL (quotient) and AH (remainder) ; arg (8-bit divisor) ; div_r8: ; 42 = 84 / 2 mov ax, 84 mov bl, 2 div bl and rax, 0x000000FF ret div_m8: ; 42 = 84 / 2 mov ax, 84 mov byte [rel m8], 2 div byte [rel m8] and rax, 0x000000FF ret ; === [ div arg ] ============================================================== ; ; --- [ 16-bit divisor arg ] --------------------------------------------------- ; ; DX:AX ; ____________________ => AX (quotient) and DX (remainder) ; arg (16-bit divisor) ; div_r16: ; 42 = 84 / 2 mov dx, 0 mov ax, 84 mov bx, 2 div bx and rax, 0x0000FFFF ret div_m16: ; 42 = 84 / 2 mov dx, 0 mov ax, 84 mov word [rel m16], 2 div word [rel m16] and rax, 0x0000FFFF ret ; === [ div arg ] ============================================================== ; ; --- [ 32-bit divisor arg ] --------------------------------------------------- ; ; EDX:EAX ; ____________________ => EAX (quotient) and EDX (remainder) ; arg (32-bit divisor) ; div_r32: ; 42 = 84 / 2 mov edx, 0 mov eax, 84 mov ebx, 2 div ebx mov rbx, 0x00000000FFFFFFFF and rax, rbx ret div_m32: ; 42 = 84 / 2 mov edx, 0 mov eax, 84 mov dword [rel m32], 2 div dword [rel m32] mov rbx, 0x00000000FFFFFFFF and rax, rbx ret ; === [ div arg ] ============================================================== ; ; --- [ 64-bit divisor arg ] --------------------------------------------------- ; ; RDX:RAX ; ____________________ => RAX (quotient) and RDX (remainder) ; arg (64-bit divisor) ; div_r64: ; 42 = 84 / 2 mov rdx, 0 mov rax, 84 mov rbx, 2 div rbx ret div_m64: ; 42 = 84 / 2 mov rdx, 0 mov rax, 84 mov qword [rel m64], 2 div qword [rel m64] ret ;imul: ; mov eax, 2 ; imul eax, 21 ; ret section .bss ; 8-bit memory variable. m8: resb 1 ; 16-bit memory variable. m16: resw 1 ; 32-bit memory variable. m32: resd 1 ; 64-bit memory variable. m64: resq 1
; A301688: Coordination sequence for node of type V2 in "krh" 2-D tiling (or net). ; 1,4,9,12,17,22,24,30,35,36,43,48,48,56,61,60,69,74,72,82,87,84,95,100,96,108,113,108,121,126,120,134,139,132,147,152,144,160,165,156,173,178,168,186,191,180,199,204,192,212,217,204,225,230,216,238,243,228,251,256,240,264,269,252,277,282,264,290,295,276,303,308,288,316,321,300,329,334,312,342,347,324,355,360,336,368,373,348,381,386,360,394,399,372,407,412,384,420,425,396 mov $5,$0 mul $0,2 mov $3,2 mov $4,1 add $4,$0 mov $0,$4 lpb $0 mov $1,$0 add $1,1 mov $3,$1 mod $1,3 mov $0,$1 trn $0,1 add $0,3 mul $3,2 div $3,$0 lpe mov $1,$3 sub $1,1 mov $2,$5 mul $2,3 add $1,$2 mov $0,$1
MelanieText1:: text "I take care of" line "injured #MON." para "I nursed this" line "BULBASAUR back to" cont "health." para "It needs a good" line "trainer to take" cont "care of it now.@@" MelanieText2:: text "I know! Would you" line "take care of this" cont "BULBASAUR?" done MelanieText3:: text "Please take care" line "of BULBASAUR!@@" MelanieText4:: text "Is BULBASAUR" line "doing well?@@" MelanieText5:: text "Oh..." line "That's too bad...@@" MelanieBulbasaurText:: text "BULBASAUR: Bubba!" line "Zoar!@@" MelanieOddishText:: text "ODDISH: Orddissh!@@" MelanieSandshrewText:: text "SANDSHREW: Pikii!@@"
; A307681: Difference between the number of diagonals and the number of sides for a convex n-gon. ; -3,-2,0,3,7,12,18,25,33,42,52,63,75,88,102,117,133,150,168,187,207,228,250,273,297,322,348,375,403,432,462,493,525,558,592,627,663,700,738,777,817,858,900,943,987,1032,1078,1125,1173,1222,1272,1323,1375,1428,1482,1537,1593,1650,1708,1767,1827,1888,1950,2013,2077,2142,2208,2275 sub $1,$0 bin $1,2 sub $1,3
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/callback_helpers.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/memory/raw_ptr.h" #include "base/path_service.h" #include "base/test/bind.h" #include "base/version.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" #include "content/public/test/url_loader_interceptor.h" #include "extensions/browser/content_verifier.h" #include "extensions/browser/content_verifier/test_utils.h" #include "extensions/browser/extensions_test.h" #include "extensions/browser/info_map.h" #include "extensions/common/constants.h" #include "extensions/common/extension_paths.h" #include "extensions/common/file_util.h" #include "extensions/common/value_builder.h" #include "mojo/public/cpp/bindings/remote.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/zlib/google/zip.h" namespace extensions { namespace { // Specifies how test ContentVerifyJob's asynchronous steps to read hash and // read contents are ordered. // Note that: // OnHashesReady: is called when hash reading is complete. // BytesRead + DoneReading: are called when content reading is complete. enum ContentVerifyJobAsyncRunMode { // None - Let hash reading and content reading continue as is asynchronously. kNone, // Hashes become available after the contents become available. kContentReadBeforeHashesReady, // The contents become available before the hashes are ready. kHashesReadyBeforeContentRead, }; std::string GetVerifiedContents(const Extension& extension) { std::string verified_contents; EXPECT_TRUE(base::ReadFileToString( file_util::GetVerifiedContentsPath(extension.path()), &verified_contents)); return verified_contents; } void WriteManifest(const base::FilePath& extension_root) { std::string json = DictionaryBuilder() .Set("manifest_version", 2) .Set("name", "Test extension") .Set("version", "1.0") .ToJSON(); base::FilePath manifest_path = extension_root.Append(base::FilePath(FILE_PATH_LITERAL("manifest.json"))); ASSERT_EQ(static_cast<int>(json.size()), base::WriteFile(manifest_path, json.data(), json.size())); } void WriteComputedHashes( const base::FilePath& extension_root, const std::map<base::FilePath, std::string>& contents) { int block_size = extension_misc::kContentVerificationDefaultBlockSize; ComputedHashes::Data computed_hashes_data; for (const auto& resource : contents) { std::vector<std::string> hashes = ComputedHashes::GetHashesForContent(resource.second, block_size); computed_hashes_data.Add(resource.first, block_size, std::move(hashes)); } base::CreateDirectory(extension_root.Append(kMetadataFolder)); ASSERT_TRUE( ComputedHashes(std::move(computed_hashes_data)) .WriteToFile(file_util::GetComputedHashesPath(extension_root))); } } // namespace class ContentVerifyJobUnittest : public ExtensionsTest { public: ContentVerifyJobUnittest() {} ContentVerifyJobUnittest(const ContentVerifyJobUnittest&) = delete; ContentVerifyJobUnittest& operator=(const ContentVerifyJobUnittest&) = delete; ~ContentVerifyJobUnittest() override {} // Helper to get files from our subdirectory in the general extensions test // data dir. base::FilePath GetTestPath(const std::string& relative_path) { base::FilePath base_path; EXPECT_TRUE(base::PathService::Get(DIR_TEST_DATA, &base_path)); return base_path.AppendASCII("content_hash_fetcher") .AppendASCII(relative_path); } void SetUp() override { ExtensionsTest::SetUp(); extension_info_map_ = base::MakeRefCounted<InfoMap>(); auto delegate = std::make_unique<MockContentVerifierDelegate>(); content_verifier_delegate_ = delegate.get(); content_verifier_ = base::MakeRefCounted<ContentVerifier>( &testing_context_, std::move(delegate)); extension_info_map_->SetContentVerifier(content_verifier_.get()); } void TearDown() override { content_verifier_->Shutdown(); content_verifier_delegate_ = nullptr; ExtensionsTest::TearDown(); } scoped_refptr<ContentVerifier> content_verifier() { return content_verifier_; } protected: ContentVerifyJob::FailureReason RunContentVerifyJob( const Extension& extension, const base::FilePath& resource_path, std::string& resource_contents, ContentVerifyJobAsyncRunMode run_mode) { TestContentVerifySingleJobObserver observer(extension.id(), resource_path); scoped_refptr<ContentVerifyJob> verify_job = new ContentVerifyJob( extension.id(), extension.version(), extension.path(), resource_path, base::DoNothing()); auto run_content_read_step = [](ContentVerifyJob* verify_job, std::string* resource_contents) { // Simulate serving |resource_contents| from |resource_path|. verify_job->Read(base::data(*resource_contents), resource_contents->size(), MOJO_RESULT_OK); verify_job->Done(); }; switch (run_mode) { case kNone: StartJob(verify_job); // Read hashes asynchronously. run_content_read_step(verify_job.get(), &resource_contents); break; case kContentReadBeforeHashesReady: run_content_read_step(verify_job.get(), &resource_contents); StartJob(verify_job); // Read hashes asynchronously. break; case kHashesReadyBeforeContentRead: StartJob(verify_job); // Wait for hashes to become ready. observer.WaitForOnHashesReady(); run_content_read_step(verify_job.get(), &resource_contents); break; } return observer.WaitForJobFinished(); } ContentVerifyJob::FailureReason RunContentVerifyJob( const Extension& extension, const base::FilePath& resource_path, std::string& resource_contents) { return RunContentVerifyJob(extension, resource_path, resource_contents, kNone); } void StartContentVerifyJob(const Extension& extension, const base::FilePath& resource_path) { auto verify_job = base::MakeRefCounted<ContentVerifyJob>( extension.id(), extension.version(), extension.path(), resource_path, base::DoNothing()); StartJob(verify_job); } // Returns an extension after extracting and loading it from a .zip file. // The extension may be expected to have verified_contents.json in it. scoped_refptr<Extension> LoadTestExtensionFromZipPathToTempDir( base::ScopedTempDir* temp_dir, const std::string& zip_directory_name, const std::string& zip_filename) { if (!temp_dir->CreateUniqueTempDir()) { ADD_FAILURE() << "Failed to create temp dir."; return nullptr; } base::FilePath unzipped_path = temp_dir->GetPath(); base::FilePath test_dir_base = GetTestPath(zip_directory_name); scoped_refptr<Extension> extension = content_verifier_test_utils::UnzipToDirAndLoadExtension( test_dir_base.AppendASCII(zip_filename), unzipped_path); // If needed, make sure there is a verified_contents.json file there as this // test cannot fetch it. if (extension && content_verifier_delegate()->GetVerifierSourceType(*extension) == ContentVerifierDelegate::VerifierSourceType::SIGNED_HASHES && !base::PathExists( file_util::GetVerifiedContentsPath(extension->path()))) { ADD_FAILURE() << "verified_contents.json not found."; return nullptr; } content_verifier_->OnExtensionLoaded(&testing_context_, extension.get()); return extension; } // Returns an extension after creating it from scratch with help of // |create_callback|. This callback is expected to create all required // extension resources in |extension_path|, including manifest.json. scoped_refptr<Extension> CreateAndLoadTestExtensionToTempDir( base::ScopedTempDir* temp_dir, absl::optional<std::map<base::FilePath, std::string>> resources_for_hashes) { if (!temp_dir->CreateUniqueTempDir()) { ADD_FAILURE() << "Failed to create temp dir."; return nullptr; } base::FilePath extension_root = temp_dir->GetPath(); WriteManifest(extension_root); if (resources_for_hashes) WriteComputedHashes(extension_root, resources_for_hashes.value()); std::string error; scoped_refptr<Extension> extension = file_util::LoadExtension( extension_root, mojom::ManifestLocation::kInternal, /*flags=*/0, &error); EXPECT_NE(nullptr, extension.get()) << " error:'" << error << "'"; content_verifier_->OnExtensionLoaded(&testing_context_, extension.get()); return extension; } MockContentVerifierDelegate* content_verifier_delegate() { DCHECK(content_verifier_); DCHECK(content_verifier_delegate_); return content_verifier_delegate_; } private: void StartJob(scoped_refptr<ContentVerifyJob> job) { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&ContentVerifyJob::Start, job, base::Unretained(content_verifier_.get()))); } scoped_refptr<InfoMap> extension_info_map_; scoped_refptr<ContentVerifier> content_verifier_; raw_ptr<MockContentVerifierDelegate> content_verifier_delegate_ = nullptr; // Owned by |content_verifier_|. content::TestBrowserContext testing_context_; }; // Tests that deleted legitimate files trigger content verification failure. // Also tests that non-existent file request does not trigger content // verification failure. TEST_F(ContentVerifyJobUnittest, DeletedAndMissingFiles) { base::ScopedTempDir temp_dir; scoped_refptr<Extension> extension = LoadTestExtensionFromZipPathToTempDir( &temp_dir, "with_verified_contents", "source_all.zip"); ASSERT_TRUE(extension.get()); base::FilePath unzipped_path = temp_dir.GetPath(); const base::FilePath::CharType kExistentResource[] = FILE_PATH_LITERAL("background.js"); base::FilePath existent_resource_path(kExistentResource); { // Make sure background.js passes verification correctly. std::string contents; base::ReadFileToString(unzipped_path.Append(existent_resource_path), &contents); EXPECT_EQ(ContentVerifyJob::NONE, RunContentVerifyJob(*extension.get(), existent_resource_path, contents)); } { // Once background.js is deleted, verification will result in HASH_MISMATCH. // Delete the existent file first. EXPECT_TRUE(base::DeleteFile(unzipped_path.Append(existent_resource_path))); // Deleted file will serve empty contents. std::string empty_contents; EXPECT_EQ(ContentVerifyJob::HASH_MISMATCH, RunContentVerifyJob(*extension.get(), existent_resource_path, empty_contents)); } { // Now ask for a non-existent resource non-existent.js. Verification should // skip this file as it is not listed in our verified_contents.json file. const base::FilePath::CharType kNonExistentResource[] = FILE_PATH_LITERAL("non-existent.js"); base::FilePath non_existent_resource_path(kNonExistentResource); // Non-existent file will serve empty contents. std::string empty_contents; EXPECT_EQ(ContentVerifyJob::NONE, RunContentVerifyJob(*extension.get(), non_existent_resource_path, empty_contents)); } { // Now create a resource foo.js which exists on disk but is not in the // extension's verified_contents.json. Verification should result in // NO_HASHES_FOR_FILE since the extension is trying to load a file the // extension should not have. const base::FilePath::CharType kUnexpectedResource[] = FILE_PATH_LITERAL("foo.js"); base::FilePath unexpected_resource_path(kUnexpectedResource); base::FilePath full_path = unzipped_path.Append(unexpected_resource_path); const std::string kContent("42"); EXPECT_EQ(static_cast<int>(kContent.size()), base::WriteFile(full_path, kContent.data(), kContent.size())); std::string contents; base::ReadFileToString(full_path, &contents); EXPECT_EQ(ContentVerifyJob::NO_HASHES_FOR_FILE, RunContentVerifyJob(*extension.get(), unexpected_resource_path, contents)); } { // Ask for the root path of the extension (i.e., chrome-extension://<id>/). // Verification should skip this request as if the resource were // non-existent. See https://crbug.com/791929. base::FilePath empty_path_resource_path(FILE_PATH_LITERAL("")); std::string empty_contents; EXPECT_EQ(ContentVerifyJob::NONE, RunContentVerifyJob(*extension.get(), empty_path_resource_path, empty_contents)); } { // Ask for the path of one of the extension's folders which exists on disk. // Verification of the folder should skip the request as if the folder // was non-existent. See https://crbug.com/791929. const base::FilePath::CharType kUnexpectedFolder[] = FILE_PATH_LITERAL("bar/"); base::FilePath unexpected_folder_path(kUnexpectedFolder); base::CreateDirectory(unzipped_path.Append(unexpected_folder_path)); std::string empty_contents; EXPECT_EQ(ContentVerifyJob::NONE, RunContentVerifyJob(*extension.get(), unexpected_folder_path, empty_contents)); } } namespace { void WriteIncorrectComputedHashes(const base::FilePath& extension_path, const base::FilePath& resource_path) { // It is important that correct computed_hashes.json already exists, because // we don't want to modify it while it is being created. "source_all.zip" // ensures we already have it. ASSERT_TRUE( base::PathExists(file_util::GetComputedHashesPath(extension_path))); base::DeleteFile(file_util::GetComputedHashesPath(extension_path)); int block_size = extension_misc::kContentVerificationDefaultBlockSize; ComputedHashes::Data incorrect_computed_hashes_data; // Write a valid computed_hashes.json with incorrect hash for |resource_path|. const std::string kFakeContents = "fake contents"; std::vector<std::string> hashes = ComputedHashes::GetHashesForContent(kFakeContents, block_size); incorrect_computed_hashes_data.Add(resource_path, block_size, std::move(hashes)); ASSERT_TRUE( ComputedHashes(std::move(incorrect_computed_hashes_data)) .WriteToFile(file_util::GetComputedHashesPath(extension_path))); } void WriteEmptyComputedHashes(const base::FilePath& extension_path) { // It is important that correct computed_hashes.json already exists, because // we don't want to modify it while it is being created. "source_all.zip" // ensures we already have it. ASSERT_TRUE( base::PathExists(file_util::GetComputedHashesPath(extension_path))); base::DeleteFile(file_util::GetComputedHashesPath(extension_path)); ComputedHashes::Data incorrect_computed_hashes_data; ASSERT_TRUE( ComputedHashes(std::move(incorrect_computed_hashes_data)) .WriteToFile(file_util::GetComputedHashesPath(extension_path))); } } // namespace // Tests that deletion of an extension resource and invalid hash for it in // computed_hashes.json won't result in bypassing corruption check. TEST_F(ContentVerifyJobUnittest, DeletedResourceAndCorruptedComputedHashes) { base::ScopedTempDir temp_dir; const base::FilePath::CharType kResource[] = FILE_PATH_LITERAL("background.js"); base::FilePath resource_path(kResource); scoped_refptr<Extension> extension = LoadTestExtensionFromZipPathToTempDir( &temp_dir, "with_verified_contents", "source_all.zip"); ASSERT_TRUE(extension.get()); // Tamper the extension: remove resource and place wrong hash for its entry in // computed_hashes.json. Reload content verifier's cache after that because // content verifier may read computed_hashes.json with old values upon // extension loading. base::FilePath unzipped_path = temp_dir.GetPath(); WriteIncorrectComputedHashes(unzipped_path, resource_path); EXPECT_TRUE( base::DeleteFile(unzipped_path.Append(base::FilePath(kResource)))); content_verifier()->ClearCacheForTesting(); { // By now in tests we serve an empty resource instead of non-existsing one. // See https://crbug.com/999727 for details. std::string empty_contents; EXPECT_EQ( ContentVerifyJob::NO_HASHES_FOR_FILE, RunContentVerifyJob(*extension.get(), resource_path, empty_contents)); } } // Tests that deletion of an extension resource and removing its entry from // computed_hashes.json won't result in bypassing corruption check. TEST_F(ContentVerifyJobUnittest, DeletedResourceAndCleanedComputedHashes) { base::ScopedTempDir temp_dir; const base::FilePath::CharType kResource[] = FILE_PATH_LITERAL("background.js"); base::FilePath resource_path(kResource); scoped_refptr<Extension> extension = LoadTestExtensionFromZipPathToTempDir( &temp_dir, "with_verified_contents", "source_all.zip"); ASSERT_TRUE(extension.get()); // Tamper the extension: remove resource and remove its entry from // computed_hashes.json. Reload content verifier's cache after that because // content verifier may read computed_hashes.json with old values upon // extension loading. base::FilePath unzipped_path = temp_dir.GetPath(); WriteEmptyComputedHashes(unzipped_path); EXPECT_TRUE( base::DeleteFile(unzipped_path.Append(base::FilePath(kResource)))); content_verifier()->ClearCacheForTesting(); { // By now in tests we serve an empty resource instead of non-existsing one. // See https://crbug.com/999727 for details. std::string empty_contents; EXPECT_EQ( ContentVerifyJob::NO_HASHES_FOR_FILE, RunContentVerifyJob(*extension.get(), resource_path, empty_contents)); } } // Tests that extension resources that are originally 0 byte behave correctly // with content verification. TEST_F(ContentVerifyJobUnittest, LegitimateZeroByteFile) { base::ScopedTempDir temp_dir; // |extension| has a 0 byte background.js file in it. scoped_refptr<Extension> extension = LoadTestExtensionFromZipPathToTempDir( &temp_dir, "zero_byte_file", "source.zip"); ASSERT_TRUE(extension.get()); base::FilePath unzipped_path = temp_dir.GetPath(); const base::FilePath::CharType kResource[] = FILE_PATH_LITERAL("background.js"); base::FilePath resource_path(kResource); { // Make sure 0 byte background.js passes content verification. std::string contents; base::ReadFileToString(unzipped_path.Append(resource_path), &contents); EXPECT_EQ(ContentVerifyJob::NONE, RunContentVerifyJob(*extension.get(), resource_path, contents)); } { // Make sure non-empty background.js fails content verification. std::string modified_contents = "console.log('non empty');"; EXPECT_EQ(ContentVerifyJob::HASH_MISMATCH, RunContentVerifyJob(*extension.get(), resource_path, modified_contents)); } } // Tests that extension resources of different interesting sizes work properly. // Regression test for https://crbug.com/720597, where content verification // always failed for sizes multiple of content hash's block size (4096 bytes). TEST_F(ContentVerifyJobUnittest, DifferentSizedFiles) { base::ScopedTempDir temp_dir; scoped_refptr<Extension> extension = LoadTestExtensionFromZipPathToTempDir( &temp_dir, "different_sized_files", "source.zip"); ASSERT_TRUE(extension.get()); base::FilePath unzipped_path = temp_dir.GetPath(); const struct { const char* name; size_t byte_size; } kFilesToTest[] = { {"1024.js", 1024}, {"4096.js", 4096}, {"8192.js", 8192}, {"8191.js", 8191}, {"8193.js", 8193}, }; for (const auto& file_to_test : kFilesToTest) { base::FilePath resource_path = base::FilePath::FromASCII(file_to_test.name); std::string contents; base::ReadFileToString(unzipped_path.AppendASCII(file_to_test.name), &contents); EXPECT_EQ(file_to_test.byte_size, contents.size()); EXPECT_EQ(ContentVerifyJob::NONE, RunContentVerifyJob(*extension.get(), resource_path, contents)); } } // Tests that if both file contents and hash are modified, corruption will still // be detected. TEST_F(ContentVerifyJobUnittest, ModifiedComputedHashes) { base::ScopedTempDir temp_dir; scoped_refptr<Extension> extension = LoadTestExtensionFromZipPathToTempDir( &temp_dir, "with_verified_contents_corrupted", "source_all.zip"); ASSERT_TRUE(extension.get()); base::FilePath unzipped_path = temp_dir.GetPath(); const base::FilePath::CharType kExistentResource[] = FILE_PATH_LITERAL("background.js"); base::FilePath existent_resource_path(kExistentResource); { // Make sure background.js passes verification correctly. std::string contents; base::ReadFileToString(unzipped_path.Append(existent_resource_path), &contents); EXPECT_EQ(ContentVerifyJob::NO_HASHES_FOR_FILE, RunContentVerifyJob(*extension.get(), existent_resource_path, contents)); } } using ContentVerifyJobWithoutSignedHashesUnittest = ContentVerifyJobUnittest; // Mark tests with extensions which intentionally don't contain // verified_contents.json. Typically these are self-hosted extension, since // there is no possibility for them to use private Chrome Web Store key to sign // hashes. // Tests that without verified_contents.json file computes_hashes.json file is // loaded correctly and appropriate error is reported when load fails. TEST_F(ContentVerifyJobWithoutSignedHashesUnittest, ComputedHashesLoad) { base::ScopedTempDir temp_dir; content_verifier_delegate()->SetVerifierSourceType( ContentVerifierDelegate::VerifierSourceType::UNSIGNED_HASHES); // Simple resource to trigger content verify job start and hashes load. const base::FilePath kResourcePath(FILE_PATH_LITERAL("script.js")); const std::string kResourceContents = "console.log('Nothing special');"; std::map<base::FilePath, std::string> resource_map = { {kResourcePath, kResourceContents}}; // Contents of corrupted computed_hashes.json file. const std::string kCorruptedContents = "not a json"; scoped_refptr<Extension> extension = CreateAndLoadTestExtensionToTempDir(&temp_dir, std::move(resource_map)); ASSERT_TRUE(extension); base::FilePath unzipped_path = temp_dir.GetPath(); { // Case where computed_hashes.json is on its place and correct. TestContentVerifySingleJobObserver observer(extension->id(), kResourcePath); content_verifier()->ClearCacheForTesting(); StartContentVerifyJob(*extension, kResourcePath); ContentHashReader::InitStatus hashes_status = observer.WaitForOnHashesReady(); EXPECT_EQ(ContentHashReader::InitStatus::SUCCESS, hashes_status); } { // Case where computed_hashes.json is corrupted. ASSERT_EQ( static_cast<int>(kCorruptedContents.size()), base::WriteFile(file_util::GetComputedHashesPath(unzipped_path), kCorruptedContents.data(), kCorruptedContents.size())); TestContentVerifySingleJobObserver observer(extension->id(), kResourcePath); content_verifier()->ClearCacheForTesting(); StartContentVerifyJob(*extension, kResourcePath); ContentHashReader::InitStatus hashes_status = observer.WaitForOnHashesReady(); EXPECT_EQ(ContentHashReader::InitStatus::HASHES_DAMAGED, hashes_status); } { // Case where computed_hashes.json doesn't exist. base::DeleteFile(file_util::GetComputedHashesPath(unzipped_path)); TestContentVerifySingleJobObserver observer(extension->id(), kResourcePath); content_verifier()->ClearCacheForTesting(); StartContentVerifyJob(*extension, kResourcePath); ContentHashReader::InitStatus hashes_status = observer.WaitForOnHashesReady(); EXPECT_EQ(ContentHashReader::InitStatus::HASHES_MISSING, hashes_status); } } // Tests that extension without verified_contents.json is checked properly. TEST_F(ContentVerifyJobWithoutSignedHashesUnittest, UnverifiedExtension) { base::ScopedTempDir temp_dir; content_verifier_delegate()->SetVerifierSourceType( ContentVerifierDelegate::VerifierSourceType::UNSIGNED_HASHES); const base::FilePath kResourceOkPath(FILE_PATH_LITERAL("script-ok.js")); const base::FilePath kResourceCorruptedPath( FILE_PATH_LITERAL("script-corrupted.js")); const base::FilePath kResourceMissingPath( FILE_PATH_LITERAL("script-missing.js")); const base::FilePath kResourceUnexpectedPath( FILE_PATH_LITERAL("script-unexpected.js")); const std::string kOkContents = "console.log('Nothing special');"; const std::string kCorruptedContents = "alert('Evil corrupted script');"; std::map<base::FilePath, std::string> resource_map = { {kResourceOkPath, kOkContents}, {kResourceCorruptedPath, kOkContents}}; scoped_refptr<Extension> extension = CreateAndLoadTestExtensionToTempDir(&temp_dir, std::move(resource_map)); ASSERT_TRUE(extension); base::FilePath unzipped_path = temp_dir.GetPath(); ASSERT_EQ(static_cast<int>(kOkContents.size()), base::WriteFile(unzipped_path.Append(kResourceOkPath), kOkContents.data(), kOkContents.size())); ASSERT_EQ( static_cast<int>(kCorruptedContents.size()), base::WriteFile(unzipped_path.Append(kResourceCorruptedPath), kCorruptedContents.data(), kCorruptedContents.size())); ASSERT_EQ(static_cast<int>(kOkContents.size()), base::WriteFile(unzipped_path.Append(kResourceUnexpectedPath), kOkContents.data(), kOkContents.size())); { // Sanity check that an unmodified file passes content verification. std::string contents; base::ReadFileToString(unzipped_path.Append(kResourceOkPath), &contents); EXPECT_EQ(ContentVerifyJob::NONE, RunContentVerifyJob(*extension.get(), kResourceOkPath, contents)); } { // Make sure a file with incorrect content (eg. corrupted one) fails content // verification. std::string contents; base::ReadFileToString(unzipped_path.Append(kResourceCorruptedPath), &contents); EXPECT_EQ(ContentVerifyJob::HASH_MISMATCH, RunContentVerifyJob(*extension.get(), kResourceCorruptedPath, contents)); } { // Make sure non-existing file doesn't fail content verification. std::string contents; base::ReadFileToString(unzipped_path.Append(kResourceMissingPath), &contents); EXPECT_EQ( ContentVerifyJob::NONE, RunContentVerifyJob(*extension.get(), kResourceMissingPath, contents)); } { // Make sure existing file fail content verification if there is no entry // for it in computed_hashes.json. std::string contents; base::ReadFileToString(unzipped_path.Append(kResourceUnexpectedPath), &contents); EXPECT_EQ(ContentVerifyJob::NO_HASHES_FOR_FILE, RunContentVerifyJob(*extension.get(), kResourceUnexpectedPath, contents)); } } // Tests that extension without any hashes (both verified_contents.json and // computed_hashes.json are missing) is checked properly. TEST_F(ContentVerifyJobWithoutSignedHashesUnittest, ExtensionWithoutHashes) { base::ScopedTempDir temp_dir; content_verifier_delegate()->SetVerifierSourceType( ContentVerifierDelegate::VerifierSourceType::UNSIGNED_HASHES); const base::FilePath kResourcePath(FILE_PATH_LITERAL("script-ok.js")); scoped_refptr<Extension> extension = CreateAndLoadTestExtensionToTempDir(&temp_dir, absl::nullopt); ASSERT_TRUE(extension); base::FilePath unzipped_path = temp_dir.GetPath(); const std::string kContents = "console.log('Nothing special');"; ASSERT_EQ(static_cast<int>(kContents.size()), base::WriteFile(unzipped_path.Append(kResourcePath), kContents.data(), kContents.size())); { // Make sure good file passes content verification. std::string contents; base::ReadFileToString(unzipped_path.Append(kResourcePath), &contents); EXPECT_EQ(ContentVerifyJob::MISSING_ALL_HASHES, RunContentVerifyJob(*extension.get(), kResourcePath, contents)); // Make sure that computed_hashes.json was not created. If we create // computed_hashes.json at this stage, we may get there hashes of // already-corrupted files. We can only computed hashes upon installation, // if these hashes are not signed. EXPECT_FALSE( base::PathExists(file_util::GetComputedHashesPath(extension->path()))); } } class ContentMismatchUnittest : public ContentVerifyJobUnittest, public testing::WithParamInterface<ContentVerifyJobAsyncRunMode> { public: ContentMismatchUnittest() {} ContentMismatchUnittest(const ContentMismatchUnittest&) = delete; ContentMismatchUnittest& operator=(const ContentMismatchUnittest&) = delete; protected: // Runs test to verify that a modified extension resource (background.js) // causes ContentVerifyJob to fail with HASH_MISMATCH. The string // |content_to_append_for_mismatch| is appended to the resource for // modification. The asynchronous nature of ContentVerifyJob can be controlled // by |run_mode|. void RunContentMismatchTest(const std::string& content_to_append_for_mismatch, ContentVerifyJobAsyncRunMode run_mode) { base::ScopedTempDir temp_dir; scoped_refptr<Extension> extension = LoadTestExtensionFromZipPathToTempDir( &temp_dir, "with_verified_contents", "source_all.zip"); ASSERT_TRUE(extension.get()); base::FilePath unzipped_path = temp_dir.GetPath(); const base::FilePath::CharType kResource[] = FILE_PATH_LITERAL("background.js"); base::FilePath existent_resource_path(kResource); { // Make sure modified background.js fails content verification. std::string modified_contents; base::ReadFileToString(unzipped_path.Append(existent_resource_path), &modified_contents); modified_contents.append(content_to_append_for_mismatch); EXPECT_EQ(ContentVerifyJob::HASH_MISMATCH, RunContentVerifyJob(*extension.get(), existent_resource_path, modified_contents, run_mode)); } } }; INSTANTIATE_TEST_SUITE_P(ContentVerifyJobUnittest, ContentMismatchUnittest, testing::Values(kNone, kContentReadBeforeHashesReady, kHashesReadyBeforeContentRead)); // Tests that content modification causes content verification failure. TEST_P(ContentMismatchUnittest, ContentMismatch) { RunContentMismatchTest("console.log('modified');", GetParam()); } // Similar to ContentMismatch, but uses a file size > 4k. // Regression test for https://crbug.com/804630. TEST_P(ContentMismatchUnittest, ContentMismatchWithLargeFile) { std::string content_larger_than_block_size( extension_misc::kContentVerificationDefaultBlockSize + 1, ';'); RunContentMismatchTest(content_larger_than_block_size, GetParam()); } // ContentVerifyJobUnittest with hash fetch interception support. class ContentVerifyJobWithHashFetchUnittest : public ContentVerifyJobUnittest { public: ContentVerifyJobWithHashFetchUnittest() : hash_fetch_interceptor_(base::BindRepeating( &ContentVerifyJobWithHashFetchUnittest::InterceptHashFetch, base::Unretained(this))) {} ContentVerifyJobWithHashFetchUnittest( const ContentVerifyJobWithHashFetchUnittest&) = delete; ContentVerifyJobWithHashFetchUnittest& operator=( const ContentVerifyJobWithHashFetchUnittest&) = delete; protected: // Responds to hash fetch request. void RespondToClientIfReady() { DCHECK(verified_contents_); if (!client_ || !ready_to_respond_) return; content::URLLoaderInterceptor::WriteResponse( std::string(), *verified_contents_, client_.get()); } void ForceHashFetchOnNextResourceLoad(const Extension& extension) { // We need to store verified_contents.json's contents so that // hash_fetch_interceptor_ can serve its request. verified_contents_ = GetVerifiedContents(extension); // Delete verified_contents.json. EXPECT_TRUE(base::DeletePathRecursively( file_util::GetVerifiedContentsPath(extension.path()))); // Clear cache so that next extension resource load will fetch hashes as // we've already deleted verified_contents.json. // Use this opportunity to base::RunLoop run_loop; content::GetIOThreadTaskRunner({})->PostTaskAndReply( FROM_HERE, base::BindOnce( [](scoped_refptr<ContentVerifier> content_verifier) { content_verifier->ClearCacheForTesting(); }, content_verifier()), run_loop.QuitClosure()); run_loop.Run(); } void set_ready_to_respond() { ready_to_respond_ = true; } private: bool InterceptHashFetch( content::URLLoaderInterceptor::RequestParams* params) { if (params->url_request.url.path_piece() != "/getsignature") return false; client_ = std::move(params->client); RespondToClientIfReady(); return true; } // Used to serve potentially delayed response to verified_contents.json. content::URLLoaderInterceptor hash_fetch_interceptor_; mojo::Remote<network::mojom::URLLoaderClient> client_; // Whether or not |client_| can respond to hash fetch request. bool ready_to_respond_ = false; // Copy of the contents of verified_contents.json. absl::optional<std::string> verified_contents_; }; // Regression test for https://crbug.com/995436. TEST_F(ContentVerifyJobWithHashFetchUnittest, ReadErrorBeforeHashReady) { base::ScopedTempDir temp_dir; scoped_refptr<Extension> extension = LoadTestExtensionFromZipPathToTempDir( &temp_dir, "with_verified_contents", "source_all.zip"); ASSERT_TRUE(extension.get()); const base::FilePath::CharType kBackgroundJS[] = FILE_PATH_LITERAL("background.js"); base::FilePath resource_path(kBackgroundJS); // First, make sure that next ContentVerifyJob run requires a hash fetch, so // that we can delay its request's response using |hash_fetch_interceptor_|. ForceHashFetchOnNextResourceLoad(*extension); TestContentVerifySingleJobObserver observer(extension->id(), resource_path); { // Then ContentVerifyJob sees a benign read error (MOJO_RESULT_ABORTED). scoped_refptr<ContentVerifyJob> verify_job = base::MakeRefCounted<ContentVerifyJob>( extension->id(), extension->version(), extension->path(), resource_path, base::DoNothing()); auto do_read_abort_and_done = [](scoped_refptr<ContentVerifyJob> job, scoped_refptr<ContentVerifier> content_verifier, base::OnceClosure done_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); job->Start(content_verifier.get()); job->Read(nullptr, 0u, MOJO_RESULT_ABORTED); job->Done(); std::move(done_callback).Run(); }; base::RunLoop run_loop; content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(do_read_abort_and_done, verify_job, content_verifier(), run_loop.QuitClosure())); run_loop.Run(); // After read error is seen, finally serve hash to |verify_job|. set_ready_to_respond(); RespondToClientIfReady(); } EXPECT_EQ(ContentVerifyJob::NONE, observer.WaitForJobFinished()); } } // namespace extensions
#pragma once #include "GeneralSummaryNodeCollectorFactory.hpp" #include "GeneralNodeCollectorParser.hpp" namespace axis { namespace application { namespace factories { namespace collectors { class GeneralSummaryNodeCollectorFactory::Pimpl { public: axis::services::language::parsing::ParseResult TryParseAny( const axis::services::language::iterators::InputIterator& begin, const axis::services::language::iterators::InputIterator& end ); CollectorBuildResult ParseAndBuildAny( const axis::services::language::iterators::InputIterator& begin, const axis::services::language::iterators::InputIterator& end, const axis::domain::analyses::NumericalModel& model, axis::application::parsing::core::ParseContext& context, SummaryNodeCollectorBuilder& builder); axis::application::output::collectors::GenericCollector& BuildCollector( CollectorType collectorType, const axis::String& targetSetName, const bool * directionsToCollect, axis::application::output::collectors::summarizers::SummaryType summaryType, SummaryNodeCollectorBuilder& builder) const; void MarkUndefinedNodeSet(const axis::String& setName, axis::application::parsing::core::ParseContext& context) const; GeneralNodeCollectorParser Parser; }; } } } } // namespace axis::application::factories::collectors
/*============================================================================= Copyright (c) 2011 Eric Niebler Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_SEGMENTED_FOLD_UNTIL_IMPL_HPP_INCLUDED) #define BOOST_FUSION_SEGMENTED_FOLD_UNTIL_IMPL_HPP_INCLUDED #include <boost/mpl/bool.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/identity.hpp> #include <boost/utility/result_of.hpp> #include <boost/type_traits/add_const.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/fusion/support/void.hpp> #include <boost/fusion/container/list/cons_fwd.hpp> #include <boost/fusion/sequence/intrinsic_fwd.hpp> #include <boost/fusion/iterator/equal_to.hpp> #include <boost/fusion/iterator/deref.hpp> #include <boost/fusion/iterator/next.hpp> #include <boost/fusion/support/is_segmented.hpp> #include <boost/fusion/sequence/intrinsic/segments.hpp> // fun(seq, state, context) // seq: a non-segmented range // state: the state of the fold so far // context: the path to the current range // // returns: (state', fcontinue) namespace boost { namespace fusion { template <typename First, typename Last> struct iterator_range; template <typename Context> struct segmented_iterator; namespace result_of { template <typename Cur, typename Context> struct make_segmented_iterator { typedef iterator_range< Cur , typename result_of::end< typename remove_reference< typename add_const< typename result_of::deref< typename Context::car_type::begin_type >::type >::type >::type >::type > range_type; typedef segmented_iterator<cons<range_type, Context> > type; }; } template <typename Cur, typename Context> typename result_of::make_segmented_iterator<Cur, Context>::type make_segmented_iterator(Cur const& cur, Context const& context) { typedef result_of::make_segmented_iterator<Cur, Context> impl_type; typedef typename impl_type::type type; typedef typename impl_type::range_type range_type; return type(cons<range_type, Context>(range_type(cur, fusion::end(*context.car.first)), context)); } namespace detail { template < typename Begin , typename End , typename State , typename Context , typename Fun , bool IsEmpty > struct segmented_fold_until_iterate_skip_empty; template < typename Begin , typename End , typename State , typename Context , typename Fun , bool IsDone = result_of::equal_to<Begin, End>::type::value > struct segmented_fold_until_iterate; template < typename Sequence , typename State , typename Context , typename Fun , bool IsSegmented = traits::is_segmented<Sequence>::type::value > struct segmented_fold_until_impl; template <typename Segments, typename State, typename Context, typename Fun> struct segmented_fold_until_on_segments; //auto push_context(cur, end, context) //{ // return push_back(context, segment_sequence(iterator_range(cur, end))); //} template <typename Cur, typename End, typename Context> struct push_context { typedef iterator_range<Cur, End> range_type; typedef cons<range_type, Context> type; static type call(Cur const& cur, End const& end, Context const& context) { return cons<range_type, Context>(range_type(cur, end), context); } }; //auto make_segmented_iterator(cur, end, context) //{ // return segmented_iterator(push_context(cur, end, context)); //} // //auto segmented_fold_until_impl(seq, state, context, fun) //{ // if (is_segmented(seq)) // { // segmented_fold_until_on_segments(segments(seq), state, context, fun); // } // else // { // return fun(seq, state, context); // } //} template < typename Sequence , typename State , typename Context , typename Fun , bool IsSegmented > struct segmented_fold_until_impl { typedef segmented_fold_until_on_segments< typename remove_reference< typename add_const< typename result_of::segments<Sequence>::type >::type >::type , State , Context , Fun > impl; typedef typename impl::type type; typedef typename impl::continue_type continue_type; static type call(Sequence& seq, State const& state, Context const& context, Fun const& fun) { return impl::call(fusion::segments(seq), state, context, fun); } }; template < typename Sequence , typename State , typename Context , typename Fun > struct segmented_fold_until_impl<Sequence, State, Context, Fun, false> { typedef typename Fun::template apply<Sequence, State, Context> apply_type; typedef typename apply_type::type type; typedef typename apply_type::continue_type continue_type; static type call(Sequence& seq, State const& state, Context const& context, Fun const& fun) { return apply_type::call(seq, state, context, fun); } }; //auto segmented_fold_until_on_segments(segs, state, context, fun) //{ // auto cur = begin(segs), end = end(segs); // for (; cur != end; ++cur) // { // if (empty(*cur)) // continue; // auto context` = push_context(cur, end, context); // state = segmented_fold_until_impl(*cur, state, context`, fun); // if (!second(state)) // return state; // } //} template <typename Apply> struct continue_wrap { typedef typename Apply::continue_type type; }; template <typename Begin, typename End, typename State, typename Context, typename Fun, bool IsEmpty> struct segmented_fold_until_iterate_skip_empty { // begin != end and !empty(*begin) typedef push_context<Begin, End, Context> push_context_impl; typedef typename push_context_impl::type next_context_type; typedef segmented_fold_until_impl< typename remove_reference< typename add_const< typename result_of::deref<Begin>::type >::type >::type , State , next_context_type , Fun > fold_recurse_impl; typedef typename fold_recurse_impl::type next_state_type; typedef segmented_fold_until_iterate< typename result_of::next<Begin>::type , End , next_state_type , Context , Fun > next_iteration_impl; typedef typename mpl::eval_if< typename fold_recurse_impl::continue_type , next_iteration_impl , mpl::identity<next_state_type> >::type type; typedef typename mpl::eval_if< typename fold_recurse_impl::continue_type , continue_wrap<next_iteration_impl> , mpl::identity<mpl::false_> >::type continue_type; static type call(Begin const& beg, End const& end, State const& state , Context const& context, Fun const& fun) { return call(beg, end, state, context, fun, typename fold_recurse_impl::continue_type()); } static type call(Begin const& beg, End const& end, State const& state , Context const& context, Fun const& fun, mpl::true_) // continue { return next_iteration_impl::call( fusion::next(beg) , end , fold_recurse_impl::call( *beg , state , push_context_impl::call(beg, end, context) , fun) , context , fun); } static type call(Begin const& beg, End const& end, State const& state , Context const& context, Fun const& fun, mpl::false_) // break { return fold_recurse_impl::call( *beg , state , push_context_impl::call(beg, end, context) , fun); } }; template <typename Begin, typename End, typename State, typename Context, typename Fun> struct segmented_fold_until_iterate_skip_empty<Begin, End, State, Context, Fun, true> { typedef segmented_fold_until_iterate< typename result_of::next<Begin>::type , End , State , Context , Fun > impl; typedef typename impl::type type; typedef typename impl::continue_type continue_type; static type call(Begin const& beg, End const& end, State const& state , Context const& context, Fun const& fun) { return impl::call(fusion::next(beg), end, state, context, fun); } }; template <typename Begin, typename End, typename State, typename Context, typename Fun, bool IsDone> struct segmented_fold_until_iterate { typedef typename result_of::empty< typename remove_reference< typename result_of::deref<Begin>::type >::type >::type empty_type; typedef segmented_fold_until_iterate_skip_empty<Begin, End, State, Context, Fun, empty_type::value> impl; typedef typename impl::type type; typedef typename impl::continue_type continue_type; static type call(Begin const& beg, End const& end, State const& state , Context const& context, Fun const& fun) { return impl::call(beg, end, state, context, fun); } }; template <typename Begin, typename End, typename State, typename Context, typename Fun> struct segmented_fold_until_iterate<Begin, End, State, Context, Fun, true> { typedef State type; typedef mpl::true_ continue_type; static type call(Begin const&, End const&, State const& state , Context const&, Fun const&) { return state; } }; template <typename Segments, typename State, typename Context, typename Fun> struct segmented_fold_until_on_segments { typedef segmented_fold_until_iterate< typename result_of::begin<Segments>::type , typename result_of::end<Segments>::type , State , Context , Fun > impl; typedef typename impl::type type; typedef typename impl::continue_type continue_type; static type call(Segments& segs, State const& state, Context const& context, Fun const& fun) { return impl::call(fusion::begin(segs), fusion::end(segs), state, context, fun); } }; } }} #endif
; A117066: Partial sums of cupolar numbers (1/3)*(n+1)*(5*n^2+7*n+3) (A096000). ; 1,11,48,140,325,651,1176,1968,3105,4675,6776,9516,13013,17395,22800,29376,37281,46683,57760,70700,85701,102971,122728,145200,170625,199251,231336,267148,306965,351075,399776,453376,512193,576555,646800,723276,806341,896363,993720,1098800,1212001,1333731,1464408,1604460,1754325,1914451,2085296,2267328,2461025,2666875,2885376,3117036,3362373,3621915,3896200,4185776,4491201,4813043,5151880,5508300,5882901,6276291,6689088,7121920,7575425,8050251,8547056,9066508,9609285,10176075,10767576,11384496,12027553,12697475,13395000,14120876,14875861,15660723,16476240,17323200,18202401,19114651,20060768,21041580,22057925,23110651,24200616,25328688,26495745,27702675,28950376,30239756,31571733,32947235,34367200,35832576,37344321,38903403,40510800,42167500 lpb $0 mov $2,$0 sub $0,1 seq $2,96000 ; Cupolar numbers: a(n) = (n+1)*(5*n^2+7*n+3)/3. add $1,$2 lpe add $1,1 mov $0,$1
; A021820: Decimal expansion of 1/816. ; 0,0,1,2,2,5,4,9,0,1,9,6,0,7,8,4,3,1,3,7,2,5,4,9,0,1,9,6,0,7,8,4,3,1,3,7,2,5,4,9,0,1,9,6,0,7,8,4,3,1,3,7,2,5,4,9,0,1,9,6,0,7,8,4,3,1,3,7,2,5,4,9,0,1,9,6,0,7,8,4,3,1,3,7,2,5,4,9,0,1,9,6,0,7,8,4,3,1,3 add $0,1 mov $1,10 pow $1,$0 mul $1,2 div $1,1632 mod $1,10 mov $0,$1
; ----------------------------------------------------------------------------- ; ZX0 decoder by Einar Saukas & introspec ; "Mega" version (412 bytes, 25% faster) ; ----------------------------------------------------------------------------- ; Parameters: ; HL: source address (compressed data) ; DE: destination address (decompressing) ; ----------------------------------------------------------------------------- SECTION code_clib SECTION code_compress_zx0 PUBLIC asm_dzx0_mega ; Enter: hl = void *src ; de = void*dst ; ; Uses: af, bc, de, hl asm_dzx0_mega: dzx0_mega: ld bc, $ffff ; preserve default offset 1 ld (dzx0m_last_offset+1), bc inc bc jr dzx0m_literals0 dzx0m_new_offset6: inc c add a, a ; obtain offset MSB jr c, dzx0m_new_offset5 dzx0m_elias_offset5: add a, a rl c rl b add a, a jp nc, dzx0m_elias_offset3 dzx0m_new_offset3: ex af, af' ; adjust for negative offset xor a sub c ret z ; check end marker ld b, a ex af, af' ld c, (hl) ; obtain offset LSB inc hl rr b ; last offset bit becomes first length bit rr c ld (dzx0m_last_offset+1), bc ; preserve new offset ld bc, 1 jr c, dzx0m_length3 ; obtain length dzx0m_elias_length3: add a, a rl c rl b add a, a jp nc, dzx0m_elias_length1 dzx0m_length1: inc bc push hl ; preserve source ld hl, (dzx0m_last_offset+1) add hl, de ; calculate destination - offset ldir ; copy from offset pop hl ; restore source add a, a ; copy from literals or new offset? jr c, dzx0m_new_offset0 dzx0m_literals0: inc c ld a, (hl) ; load another group of 8 bits inc hl add a, a ; obtain length jr c, dzx0m_literals7 dzx0m_elias_literals7: add a, a rl c rl b add a, a jp nc, dzx0m_elias_literals5 dzx0m_literals5: ldir ; copy literals add a, a ; copy from last offset or new offset? jp c, dzx0m_new_offset4 inc c add a, a ; obtain length jr c, dzx0m_reuse3 dzx0m_elias_reuse3: add a, a rl c rl b add a, a jp nc, dzx0m_elias_reuse1 dzx0m_reuse1: push hl ; preserve source ld hl, (dzx0m_last_offset+1) add hl, de ; calculate destination - offset ldir ; copy from offset pop hl ; restore source add a, a ; copy from literals or new offset? jr nc, dzx0m_literals0 dzx0m_new_offset0: inc c ld a, (hl) ; load another group of 8 bits inc hl add a, a ; obtain offset MSB jr c, dzx0m_new_offset7 dzx0m_elias_offset7: add a, a rl c rl b add a, a jr nc, dzx0m_elias_offset5 dzx0m_new_offset5: ex af, af' ; adjust for negative offset xor a sub c ret z ; check end marker ld b, a ex af, af' ld c, (hl) ; obtain offset LSB inc hl rr b ; last offset bit becomes first length bit rr c ld (dzx0m_last_offset+1), bc ; preserve new offset ld bc, 1 jr c, dzx0m_length5 ; obtain length dzx0m_elias_length5: add a, a rl c rl b add a, a jr nc, dzx0m_elias_length3 dzx0m_length3: inc bc push hl ; preserve source ld hl, (dzx0m_last_offset+1) add hl, de ; calculate destination - offset ldir ; copy from offset pop hl ; restore source add a, a ; copy from literals or new offset? jr c, dzx0m_new_offset2 dzx0m_literals2: inc c add a, a ; obtain length jr c, dzx0m_literals1 dzx0m_elias_literals1: add a, a rl c rl b ld a, (hl) ; load another group of 8 bits inc hl add a, a jr nc, dzx0m_elias_literals7 dzx0m_literals7: ldir ; copy literals add a, a ; copy from last offset or new offset? jp c, dzx0m_new_offset6 inc c add a, a ; obtain length jr c, dzx0m_reuse5 dzx0m_elias_reuse5: add a, a rl c rl b add a, a jr nc, dzx0m_elias_reuse3 dzx0m_reuse3: push hl ; preserve source ld hl, (dzx0m_last_offset+1) add hl, de ; calculate destination - offset ldir ; copy from offset pop hl ; restore source add a, a ; copy from literals or new offset? jr nc, dzx0m_literals2 dzx0m_new_offset2: inc c add a, a ; obtain offset MSB jr c, dzx0m_new_offset1 dzx0m_elias_offset1: add a, a rl c rl b ld a, (hl) ; load another group of 8 bits inc hl add a, a jr nc, dzx0m_elias_offset7 dzx0m_new_offset7: ex af, af' ; adjust for negative offset xor a sub c ret z ; check end marker ld b, a ex af, af' ld c, (hl) ; obtain offset LSB inc hl rr b ; last offset bit becomes first length bit rr c ld (dzx0m_last_offset+1), bc ; preserve new offset ld bc, 1 jr c, dzx0m_length7 ; obtain length dzx0m_elias_length7: add a, a rl c rl b add a, a jr nc, dzx0m_elias_length5 dzx0m_length5: inc bc push hl ; preserve source ld hl, (dzx0m_last_offset+1) add hl, de ; calculate destination - offset ldir ; copy from offset pop hl ; restore source add a, a ; copy from literals or new offset? jr c, dzx0m_new_offset4 dzx0m_literals4: inc c add a, a ; obtain length jr c, dzx0m_literals3 dzx0m_elias_literals3: add a, a rl c rl b add a, a jr nc, dzx0m_elias_literals1 dzx0m_literals1: ldir ; copy literals add a, a ; copy from last offset or new offset? jp c, dzx0m_new_offset0 inc c ld a, (hl) ; load another group of 8 bits inc hl add a, a ; obtain length jr c, dzx0m_reuse7 dzx0m_elias_reuse7: add a, a rl c rl b add a, a jr nc, dzx0m_elias_reuse5 dzx0m_reuse5: push hl ; preserve source ld hl, (dzx0m_last_offset+1) add hl, de ; calculate destination - offset ldir ; copy from offset pop hl ; restore source add a, a ; copy from literals or new offset? jr nc, dzx0m_literals4 dzx0m_new_offset4: inc c add a, a ; obtain offset MSB jp c, dzx0m_new_offset3 dzx0m_elias_offset3: add a, a rl c rl b add a, a jr nc, dzx0m_elias_offset1 dzx0m_new_offset1: ex af, af' ; adjust for negative offset xor a sub c ret z ; check end marker ld b, a ex af, af' ld c, (hl) ; obtain offset LSB inc hl rr b ; last offset bit becomes first length bit rr c ld (dzx0m_last_offset+1), bc ; preserve new offset ld bc, 1 jp c, dzx0m_length1 ; obtain length dzx0m_elias_length1: add a, a rl c rl b ld a, (hl) ; load another group of 8 bits inc hl add a, a jr nc, dzx0m_elias_length7 dzx0m_length7: inc bc push hl ; preserve source ld hl, (dzx0m_last_offset+1) add hl, de ; calculate destination - offset ldir ; copy from offset pop hl ; restore source add a, a ; copy from literals or new offset? jp c, dzx0m_new_offset6 dzx0m_literals6: inc c add a, a ; obtain length jp c, dzx0m_literals5 dzx0m_elias_literals5: add a, a rl c rl b add a, a jr nc, dzx0m_elias_literals3 dzx0m_literals3: ldir ; copy literals add a, a ; copy from last offset or new offset? jp c, dzx0m_new_offset2 inc c add a, a ; obtain length jp c, dzx0m_reuse1 dzx0m_elias_reuse1: add a, a rl c rl b ld a, (hl) ; load another group of 8 bits inc hl add a, a jr nc, dzx0m_elias_reuse7 dzx0m_reuse7: push hl ; preserve source dzx0m_last_offset: ld hl, 0 add hl, de ; calculate destination - offset ldir ; copy from offset pop hl ; restore source add a, a ; copy from literals or new offset? jr nc, dzx0m_literals6 jp dzx0m_new_offset6 ; -----------------------------------------------------------------------------
%include "io.inc" %define ARRAY_SIZE 13 %define DECIMAL_PLACES 5 section .data num_array dw 76, 12, 65, 19, 781, 671, 431, 761, 782, 12, 91, 25, 9 array_sum_prefix db "Sum of numbers: ",0 array_mean_prefix db "Numbers mean: ",0 decimal_point db ".",0 section .text global CMAIN CMAIN: mov ebp, esp; for correct debugging xor eax, eax mov ecx, ARRAY_SIZE sum: add ax, [num_array + 2*(ecx - 1)] ;Compute sum loop sum PRINT_STRING array_sum_prefix PRINT_UDEC 2, ax NEWLINE quotient: ;Compute quotient xor edx, edx ;divident is stored in edx:eax mov ebx, ARRAY_SIZE ;divisor div bx PRINT_STRING array_mean_prefix PRINT_UDEC 2, ax PRINT_STRING decimal_point xor eax, eax ret
// Copyright Steinwurf ApS 2014. // All Rights Reserved // // Distributed under the "BSD License". See the accompanying LICENSE.rst file. #include <kw/parameter.hpp> #include <string> #include <cstdint> #include <tuple> #include <gtest/gtest.h> #include "test_parameters.hpp" namespace { const kw::parameter<uint32_t> alpha; const kw::parameter<bool> bravo; const kw::parameter<std::string> charlie; } TEST(test_arg, convert) { }
#include "ConfigProcessor.h" #include <sys/utsname.h> #include <cerrno> #include <cstdlib> #include <cstring> #include <algorithm> #include <iostream> #include <functional> #include <Poco/DOM/Text.h> #include <Poco/DOM/Attr.h> #include <Poco/DOM/Comment.h> #include <Poco/Util/XMLConfiguration.h> #include <Common/ZooKeeper/ZooKeeperNodeCache.h> #include <Common/ZooKeeper/KeeperException.h> #include <Common/StringUtils/StringUtils.h> #define PREPROCESSED_SUFFIX "-preprocessed" using namespace Poco::XML; namespace DB { /// For cutting prerpocessed path to this base std::string main_config_path; /// Extracts from a string the first encountered number consisting of at least two digits. static std::string numberFromHost(const std::string & s) { for (size_t i = 0; i < s.size(); ++i) { std::string res; size_t j = i; while (j < s.size() && isNumericASCII(s[j])) res += s[j++]; if (res.size() >= 2) { while (res[0] == '0') res.erase(res.begin()); return res; } } return ""; } bool ConfigProcessor::isPreprocessedFile(const std::string & path) { return endsWith(Poco::Path(path).getBaseName(), PREPROCESSED_SUFFIX); } ConfigProcessor::ConfigProcessor( const std::string & path_, bool throw_on_bad_incl_, bool log_to_console, const Substitutions & substitutions_) : path(path_) , throw_on_bad_incl(throw_on_bad_incl_) , substitutions(substitutions_) /// We need larger name pool to allow to support vast amount of users in users.xml files for ClickHouse. /// Size is prime because Poco::XML::NamePool uses bad (inefficient, low quality) /// hash function internally, and its size was prime by default. , name_pool(new Poco::XML::NamePool(65521)) , dom_parser(name_pool) { if (log_to_console && !Logger::has("ConfigProcessor")) { channel_ptr = new Poco::ConsoleChannel; log = &Logger::create("ConfigProcessor", channel_ptr.get(), Poco::Message::PRIO_TRACE); } else { log = &Logger::get("ConfigProcessor"); } } ConfigProcessor::~ConfigProcessor() { if (channel_ptr) /// This means we have created a new console logger in the constructor. Logger::destroy("ConfigProcessor"); } /// Vector containing the name of the element and a sorted list of attribute names and values /// (except "remove" and "replace" attributes). /// Serves as a unique identifier of the element contents for comparison. using ElementIdentifier = std::vector<std::string>; using NamedNodeMapPtr = Poco::AutoPtr<Poco::XML::NamedNodeMap>; /// NOTE getting rid of iterating over the result of Node.childNodes() call is a good idea /// because accessing the i-th element of this list takes O(i) time. using NodeListPtr = Poco::AutoPtr<Poco::XML::NodeList>; static ElementIdentifier getElementIdentifier(Node * element) { const NamedNodeMapPtr attrs = element->attributes(); std::vector<std::pair<std::string, std::string>> attrs_kv; for (size_t i = 0, size = attrs->length(); i < size; ++i) { const Node * node = attrs->item(i); std::string name = node->nodeName(); auto subst_name_pos = std::find(ConfigProcessor::SUBSTITUTION_ATTRS.begin(), ConfigProcessor::SUBSTITUTION_ATTRS.end(), name); if (name == "replace" || name == "remove" || subst_name_pos != ConfigProcessor::SUBSTITUTION_ATTRS.end()) continue; std::string value = node->nodeValue(); attrs_kv.push_back(std::make_pair(name, value)); } std::sort(attrs_kv.begin(), attrs_kv.end()); ElementIdentifier res; res.push_back(element->nodeName()); for (const auto & attr : attrs_kv) { res.push_back(attr.first); res.push_back(attr.second); } return res; } static Node * getRootNode(Document * document) { const NodeListPtr children = document->childNodes(); for (size_t i = 0, size = children->length(); i < size; ++i) { Node * child = children->item(i); /// Besides the root element there can be comment nodes on the top level. /// Skip them. if (child->nodeType() == Node::ELEMENT_NODE) return child; } throw Poco::Exception("No root node in document"); } static bool allWhitespace(const std::string & s) { return s.find_first_not_of(" \t\n\r") == std::string::npos; } void ConfigProcessor::mergeRecursive(XMLDocumentPtr config, Node * config_root, const Node * with_root) { const NodeListPtr with_nodes = with_root->childNodes(); using ElementsByIdentifier = std::multimap<ElementIdentifier, Node *>; ElementsByIdentifier config_element_by_id; for (Node * node = config_root->firstChild(); node;) { Node * next_node = node->nextSibling(); /// Remove text from the original config node. if (node->nodeType() == Node::TEXT_NODE && !allWhitespace(node->getNodeValue())) { config_root->removeChild(node); } else if (node->nodeType() == Node::ELEMENT_NODE) { config_element_by_id.insert(ElementsByIdentifier::value_type(getElementIdentifier(node), node)); } node = next_node; } for (size_t i = 0, size = with_nodes->length(); i < size; ++i) { Node * with_node = with_nodes->item(i); bool merged = false; bool remove = false; if (with_node->nodeType() == Node::ELEMENT_NODE) { Element & with_element = dynamic_cast<Element &>(*with_node); remove = with_element.hasAttribute("remove"); bool replace = with_element.hasAttribute("replace"); if (remove && replace) throw Poco::Exception("both remove and replace attributes set for element <" + with_node->nodeName() + ">"); ElementsByIdentifier::iterator it = config_element_by_id.find(getElementIdentifier(with_node)); if (it != config_element_by_id.end()) { Node * config_node = it->second; config_element_by_id.erase(it); if (remove) { config_root->removeChild(config_node); } else if (replace) { with_element.removeAttribute("replace"); NodePtr new_node = config->importNode(with_node, true); config_root->replaceChild(new_node, config_node); } else { mergeRecursive(config, config_node, with_node); } merged = true; } } if (!merged && !remove) { NodePtr new_node = config->importNode(with_node, true); config_root->appendChild(new_node); } } } void ConfigProcessor::merge(XMLDocumentPtr config, XMLDocumentPtr with) { mergeRecursive(config, getRootNode(&*config), getRootNode(&*with)); } std::string ConfigProcessor::layerFromHost() { utsname buf; if (uname(&buf)) throw Poco::Exception(std::string("uname failed: ") + std::strerror(errno)); std::string layer = numberFromHost(buf.nodename); if (layer.empty()) throw Poco::Exception(std::string("no layer in host name: ") + buf.nodename); return layer; } void ConfigProcessor::doIncludesRecursive( XMLDocumentPtr config, XMLDocumentPtr include_from, Node * node, zkutil::ZooKeeperNodeCache * zk_node_cache, const zkutil::EventPtr & zk_changed_event, std::unordered_set<std::string> & contributing_zk_paths) { if (node->nodeType() == Node::TEXT_NODE) { for (auto & substitution : substitutions) { std::string value = node->nodeValue(); bool replace_occured = false; size_t pos; while ((pos = value.find(substitution.first)) != std::string::npos) { value.replace(pos, substitution.first.length(), substitution.second); replace_occured = true; } if (replace_occured) node->setNodeValue(value); } } if (node->nodeType() != Node::ELEMENT_NODE) return; /// Substitute <layer> for the number extracted from the hostname only if there is an /// empty <layer> tag without attributes in the original file. if (node->nodeName() == "layer" && !node->hasAttributes() && !node->hasChildNodes() && node->nodeValue().empty()) { NodePtr new_node = config->createTextNode(layerFromHost()); node->appendChild(new_node); return; } std::map<std::string, const Node *> attr_nodes; NamedNodeMapPtr attributes = node->attributes(); size_t substs_count = 0; for (const auto & attr_name : SUBSTITUTION_ATTRS) { auto subst = attributes->getNamedItem(attr_name); attr_nodes[attr_name] = subst; substs_count += static_cast<size_t>(subst == nullptr); } if (substs_count < SUBSTITUTION_ATTRS.size() - 1) /// only one substitution is allowed throw Poco::Exception("several substitutions attributes set for element <" + node->nodeName() + ">"); /// Replace the original contents, not add to it. bool replace = attributes->getNamedItem("replace"); bool included_something = false; auto process_include = [&](const Node * include_attr, const std::function<const Node * (const std::string &)> & get_node, const char * error_msg) { std::string name = include_attr->getNodeValue(); const Node * node_to_include = get_node(name); if (!node_to_include) { if (attributes->getNamedItem("optional")) node->parentNode()->removeChild(node); else if (throw_on_bad_incl) throw Poco::Exception(error_msg + name); else LOG_WARNING(log, error_msg << name); } else { Element & element = dynamic_cast<Element &>(*node); for (const auto & attr_name : SUBSTITUTION_ATTRS) element.removeAttribute(attr_name); if (replace) { while (Node * child = node->firstChild()) node->removeChild(child); element.removeAttribute("replace"); } const NodeListPtr children = node_to_include->childNodes(); for (size_t i = 0, size = children->length(); i < size; ++i) { NodePtr new_node = config->importNode(children->item(i), true); node->appendChild(new_node); } const NamedNodeMapPtr from_attrs = node_to_include->attributes(); for (size_t i = 0, size = from_attrs->length(); i < size; ++i) { element.setAttributeNode(dynamic_cast<Attr *>(config->importNode(from_attrs->item(i), true))); } included_something = true; } }; if (attr_nodes["incl"]) // we have include subst { auto get_incl_node = [&](const std::string & name) { return include_from ? include_from->getNodeByPath("yandex/" + name) : nullptr; }; process_include(attr_nodes["incl"], get_incl_node, "Include not found: "); } if (attr_nodes["from_zk"]) /// we have zookeeper subst { contributing_zk_paths.insert(attr_nodes["from_zk"]->getNodeValue()); if (zk_node_cache) { XMLDocumentPtr zk_document; auto get_zk_node = [&](const std::string & name) -> const Node * { zkutil::ZooKeeperNodeCache::ZNode znode = zk_node_cache->get(name, zk_changed_event); if (!znode.exists) return nullptr; /// Enclose contents into a fake <from_zk> tag to allow pure text substitutions. zk_document = dom_parser.parseString("<from_zk>" + znode.contents + "</from_zk>"); return getRootNode(zk_document.get()); }; process_include(attr_nodes["from_zk"], get_zk_node, "Could not get ZooKeeper node: "); } } if (attr_nodes["from_env"]) /// we have env subst { XMLDocumentPtr env_document; auto get_env_node = [&](const std::string & name) -> const Node * { const char * env_val = std::getenv(name.c_str()); if (env_val == nullptr) return nullptr; env_document = dom_parser.parseString("<from_env>" + std::string{env_val} + "</from_env>"); return getRootNode(env_document.get()); }; process_include(attr_nodes["from_env"], get_env_node, "Env variable is not set: "); } if (included_something) doIncludesRecursive(config, include_from, node, zk_node_cache, zk_changed_event, contributing_zk_paths); else { NodeListPtr children = node->childNodes(); Node * child = nullptr; for (size_t i = 0; (child = children->item(i)); ++i) doIncludesRecursive(config, include_from, child, zk_node_cache, zk_changed_event, contributing_zk_paths); } } ConfigProcessor::Files ConfigProcessor::getConfigMergeFiles(const std::string & config_path) { Files files; Poco::Path merge_dir_path(config_path); std::set<std::string> merge_dirs; /// Add path_to_config/config_name.d dir merge_dir_path.setExtension("d"); merge_dirs.insert(merge_dir_path.toString()); /// Add path_to_config/conf.d dir merge_dir_path.setBaseName("conf"); merge_dirs.insert(merge_dir_path.toString()); for (const std::string & merge_dir_name : merge_dirs) { Poco::File merge_dir(merge_dir_name); if (!merge_dir.exists() || !merge_dir.isDirectory()) continue; for (Poco::DirectoryIterator it(merge_dir_name); it != Poco::DirectoryIterator(); ++it) { Poco::File & file = *it; Poco::Path path(file.path()); std::string extension = path.getExtension(); std::string base_name = path.getBaseName(); // Skip non-config and temporary files if (file.isFile() && (extension == "xml" || extension == "conf") && !startsWith(base_name, ".")) files.push_back(file.path()); } } std::sort(files.begin(), files.end()); return files; } XMLDocumentPtr ConfigProcessor::processConfig( bool * has_zk_includes, zkutil::ZooKeeperNodeCache * zk_node_cache, const zkutil::EventPtr & zk_changed_event) { XMLDocumentPtr config = dom_parser.parse(path); std::vector<std::string> contributing_files; contributing_files.push_back(path); for (auto & merge_file : getConfigMergeFiles(path)) { try { XMLDocumentPtr with = dom_parser.parse(merge_file); merge(config, with); contributing_files.push_back(merge_file); } catch (Poco::Exception & e) { throw Poco::Exception("Failed to merge config with '" + merge_file + "': " + e.displayText()); } } std::unordered_set<std::string> contributing_zk_paths; try { Node * node = config->getNodeByPath("yandex/include_from"); XMLDocumentPtr include_from; std::string include_from_path; if (node) { /// if we include_from env or zk. doIncludesRecursive(config, nullptr, node, zk_node_cache, zk_changed_event, contributing_zk_paths); include_from_path = node->innerText(); } else { std::string default_path = "/etc/metrika.xml"; if (Poco::File(default_path).exists()) include_from_path = default_path; } if (!include_from_path.empty()) { contributing_files.push_back(include_from_path); include_from = dom_parser.parse(include_from_path); } doIncludesRecursive(config, include_from, getRootNode(config.get()), zk_node_cache, zk_changed_event, contributing_zk_paths); } catch (Poco::Exception & e) { throw Poco::Exception("Failed to preprocess config '" + path + "': " + e.displayText(), e); } if (has_zk_includes) *has_zk_includes = !contributing_zk_paths.empty(); std::stringstream comment; comment << " This file was generated automatically.\n"; comment << " Do not edit it: it is likely to be discarded and generated again before it's read next time.\n"; comment << " Files used to generate this file:"; for (const std::string & contributing_file : contributing_files) { comment << "\n " << contributing_file; } if (zk_node_cache && !contributing_zk_paths.empty()) { comment << "\n ZooKeeper nodes used to generate this file:"; for (const std::string & contributing_zk_path : contributing_zk_paths) comment << "\n " << contributing_zk_path; } comment << " "; NodePtr new_node = config->createTextNode("\n\n"); config->insertBefore(new_node, config->firstChild()); new_node = config->createComment(comment.str()); config->insertBefore(new_node, config->firstChild()); return config; } ConfigProcessor::LoadedConfig ConfigProcessor::loadConfig(bool allow_zk_includes) { bool has_zk_includes; XMLDocumentPtr config_xml = processConfig(&has_zk_includes); if (has_zk_includes && !allow_zk_includes) throw Poco::Exception("Error while loading config `" + path + "': from_zk includes are not allowed!"); ConfigurationPtr configuration(new Poco::Util::XMLConfiguration(config_xml)); return LoadedConfig{configuration, has_zk_includes, /* loaded_from_preprocessed = */ false, config_xml, path}; } ConfigProcessor::LoadedConfig ConfigProcessor::loadConfigWithZooKeeperIncludes( zkutil::ZooKeeperNodeCache & zk_node_cache, const zkutil::EventPtr & zk_changed_event, bool fallback_to_preprocessed) { XMLDocumentPtr config_xml; bool has_zk_includes; bool processed_successfully = false; try { config_xml = processConfig(&has_zk_includes, &zk_node_cache, zk_changed_event); processed_successfully = true; } catch (const Poco::Exception & ex) { if (!fallback_to_preprocessed) throw; const auto * zk_exception = dynamic_cast<const Coordination::Exception *>(ex.nested()); if (!zk_exception) throw; LOG_WARNING( log, "Error while processing from_zk config includes: " + zk_exception->message() + ". Config will be loaded from preprocessed file: " + preprocessed_path); config_xml = dom_parser.parse(preprocessed_path); } ConfigurationPtr configuration(new Poco::Util::XMLConfiguration(config_xml)); return LoadedConfig{configuration, has_zk_includes, !processed_successfully, config_xml, path}; } void ConfigProcessor::savePreprocessedConfig(const LoadedConfig & loaded_config, std::string preprocessed_dir) { if (preprocessed_path.empty()) { auto new_path = loaded_config.config_path; if (new_path.substr(0, main_config_path.size()) == main_config_path) new_path.replace(0, main_config_path.size(), ""); std::replace(new_path.begin(), new_path.end(), '/', '_'); if (preprocessed_dir.empty()) { if (!loaded_config.configuration->has("path")) { // Will use current directory auto parent_path = Poco::Path(loaded_config.config_path).makeParent(); preprocessed_dir = parent_path.toString(); Poco::Path poco_new_path(new_path); poco_new_path.setBaseName(poco_new_path.getBaseName() + PREPROCESSED_SUFFIX); new_path = poco_new_path.toString(); } else { preprocessed_dir = loaded_config.configuration->getString("path") + "/preprocessed_configs/"; } } else { preprocessed_dir += "/preprocessed_configs/"; } preprocessed_path = preprocessed_dir + new_path; auto path = Poco::Path(preprocessed_path).makeParent(); if (!path.toString().empty()) Poco::File(path).createDirectories(); } try { DOMWriter().writeNode(preprocessed_path, loaded_config.preprocessed_xml); } catch (Poco::Exception & e) { LOG_WARNING(log, "Couldn't save preprocessed config to " << preprocessed_path << ": " << e.displayText()); } } void ConfigProcessor::setConfigPath(const std::string & config_path) { main_config_path = config_path; } }
; vertical credits scroller ; somewhat generalised so will scroll all MODE 7 characters up by one pixel at a time ; then adds new row of pixels at the bottom from a fixed array ; separate routine fills the new line buffer with font data from an array of text .start_fx_creditscroll \\ Change these to adjust window that is scrolled CREDITS_shadow_addr = MODE7_VRAM_SHADOW CREDITS_end_addr = CREDITS_shadow_addr + (MODE7_char_width * MODE7_char_height) CREDITS_first_char = 1 CREDITS_last_char = MODE7_char_width \ ****************************************************************** \ * Credit Scroll FX \ ****************************************************************** \\ Scrolls entire screen up by one pixel adding new pixels from array \\ Scrolls entire screen up by one pixel adding new pixels from array FAST_SCROLL = TRUE .fx_creditscroll_scroll_up { \\ Start by updating the top line LDA #LO(CREDITS_shadow_addr) STA writeptr LDA #HI(CREDITS_shadow_addr) STA writeptr+1 \\ But we'll also be reading from the next line LDA #LO(CREDITS_shadow_addr + MODE7_char_width) STA readptr LDA #HI(CREDITS_shadow_addr + MODE7_char_width) STA readptr+1 \\ For each character row .y_loop IF FAST_SCROLL lda writeptr+0 sta readaddr+1 sta writeaddr2+1 lda writeptr+1 sta readaddr+2 sta writeaddr2+2 lda readptr+0 sta writeaddr1+1 lda readptr+1 sta writeaddr1+2 ENDIF IF FAST_SCROLL \\ First char in row LDY #CREDITS_first_char .x_loop .readaddr LDX &ffff, Y ; [4*] LDA glyph_shift_table_1-32,X ; [4*] STA top_bits+1 ; [4] .writeaddr1 LDX &ffff, Y ; [4*] LDA glyph_shift_table_2-32,X ; [4*] .top_bits ORA #0 ; [2] \\ Write the byte back to the screen .writeaddr2 STA &ffff, Y ; [4*] \\ Full width .skip INY ; [2] CPY #CREDITS_last_char ; [2] BCC x_loop ; [2*] ; 32 cycles ELSE \\ First char in row LDY #CREDITS_first_char .x_loop \\ Get top pixels from row below LDA (readptr), Y ; [5*] TAX ; [2] AND #&3 ; [2] STA top_bits + 1 ; [4] \\ Get bottom pixels from current row LDA (writeptr), Y ; [5*] AND #&FC ; [2] \\ Merge them together .top_bits ORA #0 ; [2] \\ Always add 32 ORA #32 ; [2] \\ Rotate the pixels to scroll up TAX ; [2] LDA fx_creditscroll_rotate, X ; [4*] \\ Write the byte back to the screen STA (writeptr), Y ; [5*] \\ Full width .skip INY ; [2] CPY #CREDITS_last_char ; [2] BCC x_loop ; [2*] ; 41 cycles per char ENDIF \\ Move down a row LDA readptr STA writeptr LDA readptr+1 STA writeptr+1 CLC LDA readptr ADC #MODE7_char_width STA readptr LDA readptr+1 ADC #0 STA readptr+1 \\ Check if we've reached the end? LDA readptr CMP #LO(CREDITS_end_addr) BNE y_loop LDA readptr+1 CMP #HI(CREDITS_end_addr) BNE y_loop \\ Do last line separately LDY #CREDITS_first_char .last_loop \\ Mask in top pixels from our new line LDA fx_creditscroll_new_line, Y AND #&3 STA top_bits_last+1 \\ Load last line bottom pixels LDA (writeptr), Y AND #&FC \\ Merge them together .top_bits_last ORA #0 \\ Always add 32... ORA #32 \\ Rotate them TAX LDA fx_creditscroll_rotate, X \\ Store back to screen STA (writeptr), Y \\ Entire row INY CPY #CREDITS_last_char BCC last_loop .return RTS } .fx_creditscroll_rotate_new_line { \\ First char in row LDY #CREDITS_first_char .x_loop \\ Get bottom pixels from current row LDA fx_creditscroll_new_line, Y AND #&FC ORA #32 \\ Rotate the pixels to scroll up TAX LDA fx_creditscroll_rotate, X \\ Write the byte back to the screen STA fx_creditscroll_new_line, Y \\ Full width .skip INY CPY #CREDITS_last_char BCC x_loop .return RTS } \\ Main update function .fx_creditscroll_update { \\ Set graphics white lda #144+7 jsr mode7_set_graphics_shadow_fast ; can remove this if other routine handling colours \\ Write new line of text to array JSR fx_creditscroll_write_text_line \\ Scroll everything up JSR fx_creditscroll_scroll_up .return RTS } \ ****************************************************************** \ * Credit Text FX \ ****************************************************************** .fx_creditscroll_text_ptr EQUW fx_creditscroll_text .fx_creditscroll_text_row EQUB 0 .fx_creditscroll_text_idx EQUB 0 .fx_creditscroll_write_text_line { \\ Write text into our new line LDA fx_creditscroll_text_ptr STA readptr LDA fx_creditscroll_text_ptr+1 STA readptr+1 LDX fx_creditscroll_text_row BEQ write_new_text CPX #3 BEQ write_new_text \\ Just rotate existing line JSR fx_creditscroll_rotate_new_line JMP reached_end_of_row .write_new_text LDX #MODE7_char_width-1 LDA #0 .clear_loop STA fx_creditscroll_new_line, X DEX BPL clear_loop \\ Get X start LDY #0 LDA (readptr), Y TAX \\ Set row INY .char_loop STY fx_creditscroll_text_idx \\ Get text char LDA (readptr), Y BNE not_end_of_string \\ If EOS assume EOR JMP reached_end_of_row .not_end_of_string ;JSR fx_creditscroll_get_char ; preserves X&Y \\ A is index into our font data TAY .font_addr_1 LDA mode7_font_data, Y INY STA fx_creditscroll_new_line, X \\ Next char cell INX CPX #MODE7_char_width BCS reached_end_of_row .font_addr_2 LDA mode7_font_data, Y INY STA fx_creditscroll_new_line, X \\ Next char cell INX CPX #MODE7_char_width BCS reached_end_of_row .font_addr_3 LDA mode7_font_data, Y INY STA fx_creditscroll_new_line, X \\ Next char cell INX CPX #MODE7_char_width BCS reached_end_of_row LDY fx_creditscroll_text_idx \\ Next text char INY JMP char_loop .reached_end_of_row \\ Next time do next row LDX fx_creditscroll_text_row INX CPX #3 BNE not_three \\ At row 3 need to swap to next line of font data LDA #LO(mode7_font_data_second_row) STA font_addr_1+1 STA font_addr_2+1 STA font_addr_3+1 LDA #HI(mode7_font_data_second_row) STA font_addr_1+2 STA font_addr_2+2 STA font_addr_3+2 \\ There are 6 rows in total .not_three CPX #6 BCC still_same_text \\ Next line of text LDY fx_creditscroll_text_idx \\ Skip to EOS { .loop LDA (readptr), Y BEQ done INY BNE loop .done } \\ Check whether there are any more strings INY LDA (readptr), Y CMP #&FF BNE next_line_text \\ Reset to start of text LDA #LO(fx_creditscroll_text) STA fx_creditscroll_text_ptr LDA #HI(fx_creditscroll_text) STA fx_creditscroll_text_ptr+1 \\ Or just flag not to write any more text.. JMP continue_text \\ Update text pointer .next_line_text TYA CLC ADC fx_creditscroll_text_ptr STA fx_creditscroll_text_ptr LDA fx_creditscroll_text_ptr+1 ADC #0 STA fx_creditscroll_text_ptr+1 \\ Next line of text .continue_text \\ Need to reset font data LDA #LO(mode7_font_data) STA font_addr_1+1 STA font_addr_2+1 STA font_addr_3+1 LDA #HI(mode7_font_data) STA font_addr_1+2 STA font_addr_2+2 STA font_addr_3+2 \\ Start from row 0 LDX #0 .still_same_text STX fx_creditscroll_text_row .return RTS } \ ****************************************************************** \ * Individual chars + typing \ ****************************************************************** ; char in A, at writeptr .fx_textscreen_plot_char { TAX LDY #0 LDA mode7_font_data, X STA (writeptr), Y INY LDA mode7_font_data+1, X STA (writeptr), Y INY LDA mode7_font_data+2, X STA (writeptr), Y LDY #MODE7_char_width LDA mode7_font_data_second_row, X STA (writeptr), Y INY LDA mode7_font_data_second_row+1, X STA (writeptr), Y INY LDA mode7_font_data_second_row+2, X STA (writeptr), Y RTS } .fx_textscreen_char_count EQUB 0 .fx_textscreen_max_chars EQUB 0 .fx_textscreen_type_delay EQUB 0 .fx_textscreen_type_timer EQUB 0 .fx_textscreen_plot_string { CLC TXA ADC mode7_sprites_row_addr_LO, Y STA writeptr LDA #HI(MODE7_VRAM_SHADOW) ADC mode7_sprites_row_addr_HI, Y STA writeptr+1 LDY #0 .loop LDA (readptr), Y BEQ done_loop STY loop_idx+1 JSR fx_textscreen_plot_char \\ Terminate after X chars LDX fx_textscreen_char_count INX STX fx_textscreen_char_count CPX fx_textscreen_max_chars BCS done_loop CLC LDA writeptr ADC #3 STA writeptr LDA writeptr+1 ADC #0 STA writeptr+1 .loop_idx LDY #0 INY BNE loop .done_loop RTS } .fx_textscreen_type_update { INC fx_textscreen_type_timer LDA fx_textscreen_type_timer CMP fx_textscreen_type_delay BCC no_inc INC fx_textscreen_max_chars LDA #0 STA fx_textscreen_type_timer .no_inc JMP fx_textscreen_plot_to_max } ; address of data in X,Y .fx_textscreen_plot_all { LDA #&FF STA fx_textscreen_max_chars } \\ Fall through .fx_textscreen_plot_to_max { STX fx_creditscroll_ptr STY fx_creditscroll_ptr+1 LDA #0 STA fx_textscreen_char_count .loop LDY #0 LDA (fx_creditscroll_ptr), Y CMP #&FF BEQ done_loop TAX INY LDA (fx_creditscroll_ptr), Y INY STA y_pos+1 TYA CLC ADC fx_creditscroll_ptr STA readptr LDA fx_creditscroll_ptr+1 STA readptr+1 .y_pos LDY #0 JSR fx_textscreen_plot_string LDX fx_textscreen_char_count CPX fx_textscreen_max_chars BCS done_loop ; y is updated INY TYA CLC ADC readptr STA fx_creditscroll_ptr LDA readptr+1 ADC #0 STA fx_creditscroll_ptr+1 JMP loop .done_loop RTS } .fx_textscreen_reset_type_delay { STA fx_textscreen_type_delay LDA #1 STA fx_textscreen_max_chars LDA #0 STA fx_textscreen_type_timer RTS } \ ****************************************************************** \ * Credit Font FX \ ****************************************************************** .fx_creditscroll_rotate_table { FOR n, 32, 127, 1 ; teletext codes range from 32-127 a = n AND 1 b = n AND 2 c = n AND 4 d = n AND 8 e = n AND 16 f = n AND 64 ; Pixel pattern becomes ; 1 2 -> a b -> c d ; 4 8 -> c d -> e f ; 64 16 -> e f -> a b IF (n AND 32) PRINT a,b,c,d,e,f EQUB 32 + (a * 16) + (b * 32) + (c / 4) + (d / 4) + (e / 4) + (f / 8) + (n AND 128) ELSE EQUB n ENDIF NEXT } fx_creditscroll_rotate = fx_creditscroll_rotate_table-32 IF FAST_SCROLL ; table to shift 3x2 teletext graphic up by 1 pixel row .glyph_shift_table_1 { FOR n, 32, 127, 1 ; teletext codes range from 32-127 a = n AND 1 b = (n AND 2)/2 c = (n AND 4)/4 d = (n AND 8)/8 e = (n AND 16)/16 f = (n AND 64)/64 EQUB 32 + (c*1) + (d*2) + (e*4) + (f*8) ;PRINT n NEXT } ; table to translate top 2 teletext pixels to bottom 2 .glyph_shift_table_2 { FOR n, 32, 127, 1 ; teletext codes range from 32-127 a = n AND 1 b = (n AND 2)/2 c = (n AND 4)/4 d = (n AND 8)/8 e = (n AND 16)/16 f = (n AND 64)/64 EQUB (a*16) + (b*64) NEXT } ENDIF \\ Spare character row which will get added to bottom of scroll \\ Update fn so only top two pixels (1+2) get added to bottom of scroll \\ Can rotate this row itself to shuffle new pixels onto bottom of screen .fx_creditscroll_new_line FOR n, 0, MODE7_char_width-1, 1 EQUB 0 NEXT \\ Map character ASCII values to the byte offset into our MODE 7 font \\ This is "cunning" but only works because the font has fewer than 256/6 (42) glyphs.. MACRO SET_TELETEXT_FONT_CHAR_MAP MAPCHAR 'A', 1 MAPCHAR 'B', 4 MAPCHAR 'C', 7 MAPCHAR 'D', 10 MAPCHAR 'E', 13 MAPCHAR 'F', 16 MAPCHAR 'G', 19 MAPCHAR 'H', 22 MAPCHAR 'I', 25 MAPCHAR 'J', 28 MAPCHAR 'K', 31 MAPCHAR 'L', 34 MAPCHAR 'M', 37 MAPCHAR 'a', 1 MAPCHAR 'b', 4 MAPCHAR 'c', 7 MAPCHAR 'd', 10 MAPCHAR 'e', 13 MAPCHAR 'f', 16 MAPCHAR 'g', 19 MAPCHAR 'h', 22 MAPCHAR 'i', 25 MAPCHAR 'j', 28 MAPCHAR 'k', 31 MAPCHAR 'l', 34 MAPCHAR 'm', 37 MAPCHAR 'N', 81 MAPCHAR 'O', 84 MAPCHAR 'P', 87 MAPCHAR 'Q', 90 MAPCHAR 'R', 93 MAPCHAR 'S', 96 MAPCHAR 'T', 99 MAPCHAR 'U', 102 MAPCHAR 'V', 105 MAPCHAR 'W', 108 MAPCHAR 'X', 111 MAPCHAR 'Y', 114 MAPCHAR 'Z', 117 MAPCHAR 'n', 81 MAPCHAR 'o', 84 MAPCHAR 'p', 87 MAPCHAR 'q', 90 MAPCHAR 'r', 93 MAPCHAR 's', 96 MAPCHAR 't', 99 MAPCHAR 'u', 102 MAPCHAR 'v', 105 MAPCHAR 'w', 108 MAPCHAR 'x', 111 MAPCHAR 'y', 114 MAPCHAR 'z', 117 MAPCHAR '0', 161 MAPCHAR '1', 164 MAPCHAR '2', 167 MAPCHAR '3', 170 MAPCHAR '4', 173 MAPCHAR '5', 176 MAPCHAR '6', 179 MAPCHAR '7', 182 MAPCHAR '8', 185 MAPCHAR '9', 188 MAPCHAR '?', 191 MAPCHAR '!', 194 MAPCHAR '.', 197 MAPCHAR ' ', 241 ENDMACRO SET_TELETEXT_FONT_CHAR_MAP \\ Credit text strings \\ First byte is character offset from left side of screen \\ Then text string terminted by 0 \\ If character offset is &FF this indicates no more strings \\ Currently strings just loop but could just stop! \\ New font is 3 chars wide = max 13 letters per line from 1 .fx_creditscroll_text ; centering offsets ; 1=19 2=17 3=16 4=14 5=13 6=11 7=10 8=8 9=7 a=5 b=4 c=2 d=1 ; 123456789abcd EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 7,"TELETEXTR",0 EQUS 8,"Teletext",0 EQUS 14,"DEMO",0 EQUS 17,"OF",0 EQUS 8,"TELETEXT",0 EQUS 14,"NESS",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 19,"A",0 EQUS 4,"Bitshifters",0 EQUS 5,"Production",0 EQUS 1,"",0 EQUS 1,"",0 ; Specs creds EQUS 14,"SPECS",0 EQUS 1,"",0 EQUS 5,"BBC MASTER",0 EQUS 7,"2MHZ 6502",0 EQUS 7,"128KB RAM",0 EQUS 10,"SAA5050",0 EQUS 8,"TELETEXT",0 EQUS 14,"CHIP",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 ; Code creds EQUS 10,"Code By",0 EQUS 1,"",0 EQUS 5,"Kieran and",0 EQUS 10,"simon.m",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 ; Music creds EQUS 5,"VGM Choons",0 EQUS 1,"",0 EQUS 7,"Exception",0 EQUS 17,"by",0 EQUS 8,"jrlepage",0 EQUS 1,"",0 EQUS 11,"Reggie",0 EQUS 17,"by",0 EQUS 8,"SVETLANA",0 EQUS 1,"",0 EQUS 10,"en vard",0 EQUS 5,"fyra javel",0 EQUS 17,"by",0 EQUS 7,"AbbeAbyss",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 ; Art creds EQUS 11,"Art by",0 EQUS 1,"",0 EQUS 2,"Horsenburger",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 ; Release creds EQUS 4,"Released at",0 EQUS 1,"",0 EQUS 7,"Nova 2017",0 EQUS 13,"Devon",0 EQUS 4,"24 Jun 2017",0 EQUS 1," ",0 EQUS 1,"",0 EQUS 1,"",0 ; Thanks EQUS 4,"Bitshifters",0 EQUS 7,"Thanks...",0 EQUS 1,"",0 EQUS 2,"Nick Jameson",0 EQUS 2,"Horsenburger",0 EQUS 11,"Rawles",0 EQUS 10,"Edit.tf",0 EQUS 11,"jsbeeb",0 EQUS 10,"BeebAsm",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 ; Greets EQUS 2,"Greetz to...",0 EQUS 1,"",0 EQUS 1,"Raquel Meyers",0 EQUS 1,"Steve Horsley",0 EQUS 2,"Simon Rawles",0 EQUS 10,"Rich TW",0 EQUS 2,"Matt Godbolt",0 EQUS 4,"Puppeh.CRTC",0 EQUS 7,"rc55.CRTC",0 EQUS 1,"Inverse Phase",0 EQUS 14,"crtc",0 EQUS 11,"DESiRE",0 EQUS 10,"Ate Bit",0 EQUS 2,"Stardot Crew",0 EQUS 1,"Teletext Crew",0 EQUS 1,"",0 EQUS 4,"Everyone at",0 EQUS 5,"the party!",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 IF 1 EQUS 2,"Thanks for",0 EQUS 7,"Watching!",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 EQUS 1,"",0 ENDIF EQUS &FF \\ How to do a single string ;.fx_textscreen_plot_bs ;{ ; LDA #LO(text_addr):STA readptr:LDA #HI(text_addr):STA readptr+1 ; LDX #4:LDY#4:JMP fx_textscreen_plot_string ; .text_addr EQUS "BITSHIFTERS", 0 ;} .fx_textscreen_type_presents { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 3,14,"PRESENTS...", 0 EQUS &FF } .fx_textscreen_type_weather { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 4,6,"WEATHER",0 EQUS 4,8, "FORECAST", 0 EQUS 17,11,"FOR", 0 EQUS 8,14, "BUDLEIGH", 0 EQUS 5,16, "SALTERTON", 0 EQUS &FF } .fx_textscreen_type_oldschool { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 7,5,"OUR",0 EQUS 4,7, "TELETEXT", 0 EQUS 17,9,"TRIBUTE", 0 EQUS 8,12,"TO", 0 EQUS 4,15, "OLD SCHOOL", 0 EQUS 10,18, "CREATED",0 EQUS 20,20, "FOR...", 0 EQUS &FF } .fx_textscreen_type_plasma { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 4,6,"LETS START",0 EQUS 4,9, "WITH", 0 EQUS 17,12,"SOME", 0 EQUS 8,15, "PLASMA...", 0 EQUS &FF } .fx_textscreen_type_interference { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 14,6, "RUN",0 EQUS 24,9, "THE", 0 EQUS 2,12, "INTERFERENCE", 0 EQUS &FF } .fx_textscreen_type_rotozoom { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 5,9,"ROTOZOOM..",0 EQUS &FF } .fx_textscreen_type_particles { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 4,6, "PARTICLE",0 EQUS 8,9, "SYSTEM", 0 EQUS 12,12,"ENGAGED!", 0 EQUS &FF } .fx_textscreen_type_vectortext { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 6,6, "TIME TO",0 EQUS 5,9, "CALL IN", 0 EQUS 4,12,"BRESENHAM", 0 EQUS &FF } .fx_textscreen_type_vectorballs { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 4,6, "SPRITES",0 EQUS 5,9, "PLUS",0 EQUS 5,12,"VECTORS", 0 EQUS 4,15,"EQUALS...", 0 EQUS &FF } .fx_textscreen_type_3dshapes { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 4,6,"BRINGING",0 EQUS 5,9, "TELETEXT", 0 EQUS 5,12,"TO THE 3RD", 0 EQUS 4,15,"DIMENSION!", 0 EQUS &FF } .fx_textscreen_type_dotscroller { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 4,6,"SCROLLER",0 EQUS 5,9, "THAT IS", 0 EQUS 5,12,"IMPOSSIBLE", 0 EQUS 4,15,"TO READ..", 0 EQUS &FF } .fx_textscreen_type_credits { LDX #LO(textscreen_data):LDY #HI(textscreen_data):JMP fx_textscreen_type_update .textscreen_data EQUS 4,6,"TELETEXTR",0 EQUS 4,8, "DEMO", 0 EQUS 17,11,"MADNESS", 0 EQUS 8,14, "CREATED", 0 EQUS 5,16, "BY", 0 EQUS &FF } RESET_MAPCHAR .mode7_font_data ; we use 16/25 lines of this screen INCBIN "data/font_5x5_shifted_trimmed.mode7.bin" mode7_font_data_second_row = mode7_font_data + 40 .end_fx_creditscroll
; A075753: Smallest prime factor of n-th odd triangular number. ; Submitted by Jon Maiga ; 3,3,3,3,5,7,3,3,3,3,11,5,3,3,3,3,5,19,3,3,3,3,23,5,3,3,3,3,29,31,3,3,3,3,5,37,3,3,3,3,41,5,3,3,3,3,5,7,3,3,3,3,53,5,3,3,3,3,7,11,3,3,3,3,5,7,3,3,3,3,11,5,3,3,3,3,5,79,3,3,3,3,83,5,3,3,3,3,89,7,3,3,3,3,5,97,3,3,3 mov $2,$0 mul $0,2 mod $2,2 add $0,$2 seq $0,121937 ; a(n) = least m >= 2 such that (n mod m) > (n+2 mod m). div $0,2 mul $0,2 add $0,1
/** * This software is distributed under the terms of the MIT License. * Copyright (c) 2020 LXRobotics. * Author: Alexander Entinger <alexander.entinger@lxrobotics.com> * Contributors: https://github.com/107-systems/107-Arduino-UAVCAN/graphs/contributors. */ #ifndef ARDUINO_UAVCAN_TYPES_UAVCAN_FILE_READ_1_0_HPP_ #define ARDUINO_UAVCAN_TYPES_UAVCAN_FILE_READ_1_0_HPP_ /************************************************************************************** * INCLUDE **************************************************************************************/ #include <libcanard/canard.h> #include <types/uavcan/file/Read_1_0.h> /************************************************************************************** * NAMESPACE **************************************************************************************/ namespace uavcan { namespace file { namespace Read_1_0 { /************************************************************************************** * CLASS DECLARATION **************************************************************************************/ template <CanardPortID ID = uavcan_file_Read_1_0_FIXED_PORT_ID_> class Request { public: uavcan_file_Read_Request_1_0 data; static constexpr CanardPortID PORT_ID = ID; static constexpr size_t MAX_PAYLOAD_SIZE = uavcan_file_Read_Request_1_0_SERIALIZATION_BUFFER_SIZE_BYTES_; static constexpr CanardTransferKind TRANSFER_KIND = CanardTransferKindMessage; Request() { uavcan_file_Read_Request_1_0_initialize_(&data); } Request(Request const & other) { memcpy(&data, &other.data, sizeof(data)); } static Request deserialize(CanardTransfer const & transfer) { Request<ID> i; size_t inout_buffer_size_bytes = transfer.payload_size; uavcan_file_Read_Request_1_0_deserialize_(&i.data, (uint8_t *)(transfer.payload), &inout_buffer_size_bytes); return i; } size_t serialize(uint8_t * payload) const { size_t inout_buffer_size_bytes = Request<ID>::MAX_PAYLOAD_SIZE; return (uavcan_file_Read_Request_1_0_serialize_(&data, payload, &inout_buffer_size_bytes) < NUNAVUT_SUCCESS) ? 0 : inout_buffer_size_bytes; } }; template <CanardPortID ID = uavcan_file_Read_1_0_FIXED_PORT_ID_> class Response { public: uavcan_file_Read_Response_1_0 data; static constexpr CanardPortID PORT_ID = ID; static constexpr size_t MAX_PAYLOAD_SIZE = uavcan_file_Read_Response_1_0_SERIALIZATION_BUFFER_SIZE_BYTES_; static constexpr CanardTransferKind TRANSFER_KIND = CanardTransferKindMessage; Response() { uavcan_file_Read_Response_1_0_initialize_(&data); } Response(Response const & other) { memcpy(&data, &other.data, sizeof(data)); } static Response deserialize(CanardTransfer const & transfer) { Response<ID> i; size_t inout_buffer_size_bytes = transfer.payload_size; uavcan_file_Read_Response_1_0_deserialize_(&i.data, (uint8_t *)(transfer.payload), &inout_buffer_size_bytes); return i; } size_t serialize(uint8_t * payload) const { size_t inout_buffer_size_bytes = Response<ID>::MAX_PAYLOAD_SIZE; return (uavcan_file_Read_Response_1_0_serialize_(&data, payload, &inout_buffer_size_bytes) < NUNAVUT_SUCCESS) ? 0 : inout_buffer_size_bytes; } }; /************************************************************************************** * NAMESPACE **************************************************************************************/ } /* Read_1_0 */ } /* file */ } /* uavcan */ #endif /* ARDUINO_UAVCAN_TYPES_UAVCAN_FILE_READ_1_0_HPP_ */
;; ;; Copyright (c) 2012-2018, Intel Corporation ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, ;; this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; * Neither the name of Intel Corporation nor the names of its contributors ;; may be used to endorse or promote products derived from this software ;; without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;; %define FUNC submit_job_hmac_sha_384_avx2 %define SHA_X_DIGEST_SIZE 384 %include "avx2/mb_mgr_hmac_sha_512_submit_avx2.asm"
;------------------------------------------------------------------------------- ; MSP430 Assembler Code Template for use with TI Code Composer Studio ; ; ;------------------------------------------------------------------------------- .cdecls C,LIST,"msp430.h" ; Include device header file ;------------------------------------------------------------------------------- .def RESET ; Export program entry-point to ; make it known to linker. .data list1 .word 0,0,0,0 count .word 0 ;------------------------------------------------------------------------------- .text ; Assemble into program memory. .retain ; Override ELF conditional linking ; and retain current section. .retainrefs ; And retain any sections that have ; references to current section. ;------------------------------------------------------------------------------- RESET mov.w #__STACK_END,SP ; Initialize stackpointer StopWDT mov.w #WDTPW|WDTHOLD,&WDTCTL ; Stop watchdog timer ;------------------------------------------------------------------------------- ; Main loop here ;------------------------------------------------------------------------------- ;0x 2be5 1cf0 6549 a0d1 mainloop push #0x2be5 push #0x1cf0 push #0x6549 push #0xa0d1 mov.w #list1,r4 add.w #6,r4 clrc clr r10 loop1 cmp.w #4,count jz setlastbit inc count pop 0(r4) rlc.w 0(r4) jc carryvar jnc carryyok carryvar add.w r10,0(r4) decd r4 mov.w #1,r10 jmp loop1 carryyok add.w r10,0(r4) decd r4 mov.w #0,r10 jmp loop1 setlastbit mov.w #list1,r4 add.w #6,r4 add.w r10,0(r4) mov.w #0,count mov.w #list1,r4 jmp yerlestir yerlestir cmp #4,count jz bitti inc count mov.w SP,r15 push 0(r4) incd r4 jmp yerlestir bitti jmp $ ;------------------------------------------------------------------------------- ; Stack Pointer definition ;------------------------------------------------------------------------------- .global __STACK_END .sect .stack ;------------------------------------------------------------------------------- ; Interrupt Vectors ;------------------------------------------------------------------------------- .sect ".reset" ; MSP430 RESET Vector .short RESET
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/rtp_rtcp/source/rtp_generic_frame_descriptor.h" #include "rtc_base/checks.h" namespace webrtc { constexpr size_t RtpGenericFrameDescriptor::kMaxNumFrameDependencies; RtpGenericFrameDescriptor::RtpGenericFrameDescriptor() = default; int RtpGenericFrameDescriptor::TemporalLayer() const { RTC_DCHECK(FirstPacketInSubFrame()); return temporal_layer_; } void RtpGenericFrameDescriptor::SetTemporalLayer(int temporal_layer) { RTC_DCHECK_GE(temporal_layer, 0); RTC_DCHECK_LE(temporal_layer, 7); temporal_layer_ = temporal_layer; } uint8_t RtpGenericFrameDescriptor::SpatialLayersBitmask() const { RTC_DCHECK(FirstPacketInSubFrame()); return spatial_layers_; } void RtpGenericFrameDescriptor::SetSpatialLayersBitmask( uint8_t spatial_layers) { RTC_DCHECK(FirstPacketInSubFrame()); spatial_layers_ = spatial_layers; } uint16_t RtpGenericFrameDescriptor::FrameId() const { RTC_DCHECK(FirstPacketInSubFrame()); return frame_id_; } void RtpGenericFrameDescriptor::SetFrameId(uint16_t frame_id) { RTC_DCHECK(FirstPacketInSubFrame()); frame_id_ = frame_id; } rtc::ArrayView<const uint16_t> RtpGenericFrameDescriptor::FrameDependenciesDiffs() const { RTC_DCHECK(FirstPacketInSubFrame()); return rtc::MakeArrayView(frame_deps_id_diffs_, num_frame_deps_); } bool RtpGenericFrameDescriptor::AddFrameDependencyDiff(uint16_t fdiff) { RTC_DCHECK(FirstPacketInSubFrame()); if (num_frame_deps_ == kMaxNumFrameDependencies) return false; if (fdiff == 0) return false; RTC_DCHECK_LT(fdiff, 1 << 14); RTC_DCHECK_GT(fdiff, 0); frame_deps_id_diffs_[num_frame_deps_] = fdiff; num_frame_deps_++; return true; } } // namespace webrtc
; int vfprintf(FILE *stream, const char *format, void *arg) INCLUDE "clib_cfg.asm" SECTION code_stdio ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $02 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC vfprintf_callee EXTERN asm_vfprintf vfprintf_callee: pop af pop bc pop de pop ix push af jp asm_vfprintf ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC vfprintf_callee EXTERN vfprintf_unlocked_callee defc vfprintf_callee = vfprintf_unlocked_callee ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
BerryTreeScript:: ; Display the "It's a fruit-bearing tree." text call EnableAutoTextBoxDrawing ld hl, FruitTreeText call PrintText ; Check to see if the player can get a berry from this tree right now ld a, [wWhichTrade] ; Which tree is this? dec a ld c, a ; We need this in register c ld b, 2 ; We want to read this value to see if it's been taken or not ld hl, W_BERRYTREEFLAGS predef FlagActionPredef ld a, c ; Let's get the result of that check and a ; Make sure the flag isn't set jp nz, .NothingHereScript ; If it is, you got the berry, so the tree is empty ; Time to give the berry ld a, [wWhichTrade] dec a ld c, a ld b, 0 ld hl, BerryTable add hl, bc ld a, [hl] ld b, a ld c, 1 call GiveItem jr nc, .BagFull ; Mark the berry as taken ld a, [wWhichTrade] ; Which tree is this? dec a ld c, a ; We need this in c ld b, 1 ; We want to set this tree's bit ld hl, W_BERRYTREEFLAGS predef FlagActionPredef ; Show "Found (Berry Name)!" text ld hl, FoundBerryText jr .print ; Runs if the berry has already been taken from this tree .NothingHereScript ld hl, NoBerryText jr .print ; Runs when the bag is full .BagFull ld hl, PackFullText .print call PrintText ret FruitTreeText: text "It's a fruit-" line "bearing tree." prompt db "@" NoBerryText: text "Looks like there's" line "nothing here." done db "@" FoundBerryText: TX_FAR _FoundItemText db $0B db "@" PackFullText: TX_FAR _NoMoreRoomForItemText db "@" ; The table is not terminated, so don't use invalid tree numbers BerryTable: db ORAN_BERRY;ORAN_BERRY ; Route 1 db PARLYZ_HEAL;CHERI ; Route 2, Tree 1 db ANTIDOTE;PECHA_BERRY ; Pewter City, Tree 1 db AWAKENING;CHESTO_BERRY ; Pewter City, Tree 2 db PARLYZ_HEAL;CHERI_BERRY ; route 8 db SITRUS_BERRY ; route 11 db ANTIDOTE;PECHA route 5 db ORAN_BERRY ; route 4 db FULL_HEAL;LUM_BERRY ; route 4 db ANTIDOTE;PECHA_BERRY ; route 15 db PARLYZ_HEAL;ORAN_BERRY ; route 16 db ANTIDOTE;PECHA_BERRY ; Route 2, Tree 2 db FULL_HEAL;;ORAN_BERRY ; Viridian Forest db SITRUS_BERRY;SITRUS_BERRY ; Route 7 db SITRUS_BERRY;SITRUS_BERRY ; none db SITRUS_BERRY;SITRUS_BERRY ; none BerryReset:: ; Called to reset berry trees ; Happens when the berry counter hits 0 ld a, [wBerryStepCounter + 1] cp a, $4 ret nz xor a ld hl, W_BERRYTREEFLAGS ld [hli],a ld [hli],a ld [hli],a ld [hl],a ;daycare ld hl, wDayCareInUse bit 0, [hl];anybody there? ret z set 2,[hl];set baby ret ;BerryReset:: ;Shorter reset, good for testing. ; Called to reset berry trees ; Happens when the berry counter hits 0 ;xor a ;ld hl, W_BERRYTREEFLAGS ;ld [hli],a ;ld [hl],a ;ret
; Tell the Assembler that are loaded at offset 0x7c00 [org 0x7c00] [bits 16] ; Memory location where our C kernel will be loaded ROOTDIRECTORY_OFFSET equ 0x1000 KERNEL_OFFSET equ 0x1200 ; Number of the sectors that we are reading during the loading of the C kernel NUMBER_OF_SECTORS_TO_READ equ 0x4 jmp start ; Jump over the BPB directly to start of the boot loader ;********************************************* ; BIOS Parameter Block (BPB) for FAT12 ;********************************************* bpbOEM db "KAOS " bpbBytesPerSector: DW 512 bpbSectorsPerCluster: DB 1 bpbReservedSectors: DW 1 bpbNumberOfFATs: DB 2 bpbRootEntries: DW 224 bpbTotalSectors: DW 2880 bpbMedia: DB 0xF0 bpbSectorsPerFAT: DW 9 bpbSectorsPerTrack: DW 18 bpbHeadsPerCylinder: DW 2 bpbHiddenSectors: DD 0 bpbTotalSectorsBig: DD 0 bsDriveNumber: DB 0 bsUnused: DB 0 bsExtBootSignature: DB 0x29 bsSerialNumber: DD 0xa0a1a2a3 bsVolumeLabel: DB "KAOS DRIVE " bsFileSystem: DB "FAT12 " ; Start of the boot loader code start: ; Setup the ds register mov ax, 0 mov ds, ax ; Prepare the stack mov bp, 0x8000 mov sp, bp ; Set the video mode to 80x25 ; This is needed afterwards so that we can print out data ; in the Protected Mode through 0xB8000 mov ah, 00h mov al, 03h int 0x10 ; Switch to protected mode call switch_to_protected_mode jmp $ ;============================================= ; Input String is in register "si" ;============================================= printline: mov al, [si] cmp al, 0 je end_printline int 0x10 inc si jmp printline end_printline: ret ;============================================= ; Switches the CPU into the x32 Protected Mode ;============================================= switch_to_protected_mode: cli lgdt [gdt_descriptor] mov eax, cr0 or eax, 0x1 mov cr0, eax jmp CODE_SEGMENT:start_protected_mode ;==================================================== ; Here begins the 32 bit code for the Protected Mode ;==================================================== [bits 32] start_protected_mode: ; Setup the Data Segment registers mov ax, DATA_SEGMENT mov ds, ax mov ss, ax mov es, ax mov fs, ax mov gs, ax ; Setup the stack mov ebp, 0x90000 mov esp, ebp ; Print out a character mov al, 'A' mov edx, 0xb8000 mov al, 'A' mov ah, 0x0f mov [edx], ax add edx, 2 ; Print out a simple welcome message ; mov ebx, welcome_message ; call printstring ; Jump into the C kernel loaded from the FAT12 at 0x1000 ;call KERNEL_OFFSET jmp $ welcome_message: db 'Booting...', 0 disk_read_error_message: db 'Read error!', 0 DataSectorBeginning: dw 0x0000 BOOT_DRIVE: db 0 absoluteSector db 0x00 absoluteHead db 0x00 absoluteTrack db 0x00 KernelName db "KERNEL BIN" KernelError db "Not found", 0 cluster dw 0x0000 ;============================================= ; Definition of the GDT, needed for the PM ;============================================= gdt_start: ; Null Descriptor gdt_null: dd 0x0 dd 0x0 ; Code Segment Descriptor gdt_code: dw 0xffff dw 0x0 db 0x0 db 10011010b db 11001111b db 0x0 ; Data Segment Descriptor gdt_data: dw 0xffff dw 0x0 db 0x0 db 10010010b db 11001111b db 0x0 gdt_end: ;============================================= ; Definition of the GDT Descriptor ;============================================= gdt_descriptor: dw gdt_end - gdt_start - 1 ; Size of the GDT dd gdt_start ; Start address of the GDT CODE_SEGMENT equ gdt_code - gdt_start DATA_SEGMENT equ gdt_data - gdt_start ; Boot Sector Padding times 510-($-$$) db 0 dw 0xaa55
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2020 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov //////////////////////////////////////////////////////////////////////////////// #ifndef IRESEARCH_SEARCH_RANGE_H #define IRESEARCH_SEARCH_RANGE_H #include "utils/hash_utils.hpp" namespace iresearch { enum class BoundType { UNBOUNDED, INCLUSIVE, EXCLUSIVE }; template<typename T> struct search_range { T min{}; T max{}; BoundType min_type = BoundType::UNBOUNDED; BoundType max_type = BoundType::UNBOUNDED; size_t hash() const noexcept { using bound_type = typename std::underlying_type<BoundType>::type; const auto hash0 = hash_combine( std::hash<decltype(min)>()(min), std::hash<decltype(max)>()(max)); const auto hash1 = hash_combine( std::hash<bound_type>()(static_cast<bound_type>(min_type)), std::hash<bound_type>()(static_cast<bound_type>(max_type))); return hash_combine(hash0, hash1); } bool operator==(const search_range& rhs) const noexcept { return min == rhs.min && min_type == rhs.min_type && max == rhs.max && max_type == rhs.max_type; } bool operator!=(const search_range& rhs) const noexcept { return !(*this == rhs); } }; // search_range } namespace std { template<typename T> struct hash<::iresearch::search_range<T>> { size_t operator()(const ::iresearch::search_range<T>& value) { return value.hash(); } }; } #endif // IRESEARCH_SEARCH_RANGE_H
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "oneflow/core/graph/boxing/slice_boxing_sub_task_graph_builder.h" #include "oneflow/core/register/tensor_slice_view.h" #include "oneflow/core/common/balanced_splitter.h" #include "oneflow/core/graph/slice_boxing_task_node.h" #include "oneflow/core/graph/boxing/sub_task_graph_builder_util.h" #include "oneflow/core/job/parallel_distribution_util.h" #include "oneflow/core/common/id_util.h" #include "oneflow/core/graph/id_serialization.h" #include "oneflow/core/device/cpu_stream_index.h" #ifdef WITH_CUDA #include "oneflow/core/device/cuda_stream_index.h" #endif namespace oneflow { namespace { void GroupParallelIdByMachine(const ParallelDesc& pd, HashMap<int64_t, std::vector<int64_t>>* machine_id2parallel_ids) { FOR_RANGE(int64_t, parallel_id, 0, pd.parallel_num()) { int64_t machine_id = CHECK_JUST(pd.MachineId4ParallelId(parallel_id)); (*machine_id2parallel_ids)[machine_id].push_back(parallel_id); } } bool ContainsEmptySlice(const std::vector<TensorSliceView>& slices) { return std::any_of(slices.cbegin(), slices.cend(), [](const TensorSliceView& slice) { return slice.IsEmpty(); }); } bool IsCopyContiguous(const TensorSliceView& src, const TensorSliceView& dst) { CHECK_EQ(src.range_vec().size(), dst.range_vec().size()); FOR_RANGE(int64_t, i, 1, src.range_vec().size()) { if (src.range_vec().at(i) != dst.range_vec().at(i)) { return false; } } return true; } bool IsSameDevice(const ParallelDesc& in_pd, const ParallelDesc& out_pd, const int64_t in_parallel_id, const int64_t out_parallel_id) { return in_pd.device_type() == out_pd.device_type() && CHECK_JUST(in_pd.DeviceId4ParallelId(in_parallel_id)) == CHECK_JUST(out_pd.DeviceId4ParallelId(out_parallel_id)); } } // namespace Maybe<SubTskGphBuilderStatus> SliceBoxingSubTskGphBuilder::Build( SubTskGphBuilderCtx* ctx, const std::vector<TaskNode*>& sorted_in_tasks, std::vector<TaskNode*>* sorted_out_tasks, std::vector<std::vector<TaskNode*>>* sorted_ctrl_tasks, const ParallelDesc& in_parallel_desc, const ParallelDesc& out_parallel_desc, const LogicalBlobId& lbi, const BlobDesc& logical_blob_desc, const SbpParallel& in_sbp_parallel, const SbpParallel& out_sbp_parallel, const Shape& time_shape) const { if (SubTskGphBuilderUtil::BlobHasDynamicShape(logical_blob_desc)) { return Error::BoxingNotSupportedError(); } if (!SubTskGphBuilderUtil::IsDeviceTypeCPUOrGPU(in_parallel_desc)) { return Error::BoxingNotSupportedError(); } if (!SubTskGphBuilderUtil::IsDeviceTypeCPUOrGPU(out_parallel_desc)) { return Error::BoxingNotSupportedError(); } if (SubTskGphBuilderUtil::HasEmptySliceIfSplit(in_parallel_desc.parallel_num(), in_sbp_parallel, logical_blob_desc)) { return Error::BoxingNotSupportedError(); } if (SubTskGphBuilderUtil::HasEmptySliceIfSplit(out_parallel_desc.parallel_num(), out_sbp_parallel, logical_blob_desc)) { return Error::BoxingNotSupportedError(); } if (!(SubTskGphBuilderUtil::IsBoxingS2B(in_sbp_parallel, out_sbp_parallel) || SubTskGphBuilderUtil::IsBoxingS2S(in_sbp_parallel, out_sbp_parallel) || SubTskGphBuilderUtil::IsBoxingP2S(in_sbp_parallel, out_sbp_parallel) || SubTskGphBuilderUtil::IsBoxingP2B(in_sbp_parallel, out_sbp_parallel) || SubTskGphBuilderUtil::IsBoxingB2S(in_sbp_parallel, out_sbp_parallel))) { return Error::BoxingNotSupportedError(); } const auto GetBoxingGpuThrdId = [](int64_t machine_id, int64_t dev_id, CudaWorkType work_type) -> int64_t { int64_t thrd_id = -1; #ifdef WITH_CUDA DeviceId device_id{static_cast<DeviceId::rank_t>(machine_id), DeviceType::kGPU, static_cast<DeviceId::device_index_t>(dev_id)}; auto* generator = dynamic_cast<CudaStreamIndexGenerator*>( Global<IDMgr>::Get()->GetStreamIndexGeneratorManager()->GetGenerator(device_id)); CHECK_NOTNULL(generator); StreamId::stream_index_t stream_index = 0; if (work_type == CudaWorkType::kCopyH2D) { stream_index = generator->GenerateH2DStreamIndex(); } else if (work_type == CudaWorkType::kCopyD2H) { stream_index = generator->GenerateD2HStreamIndex(); } else if (work_type == CudaWorkType::kMix) { stream_index = generator->GenerateMixStreamIndex(); } else { UNIMPLEMENTED(); } thrd_id = SerializeStreamIdToInt64(StreamId{device_id, stream_index}); #else UNIMPLEMENTED(); #endif return thrd_id; }; const auto NewEdge = [&ctx]() -> TaskEdge* { return ctx->task_graph()->NewEdge(); }; const auto CreateBoxingNode121 = [&ctx, &lbi, &GetBoxingGpuThrdId]( const ParallelDesc& pd, const int64_t parallel_id, const TensorSliceView& slice, SliceBoxingTaskMode mode) -> SliceBoxingTaskNode* { SliceBoxingTaskNode* node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>(); const int64_t machine_id = CHECK_JUST(pd.MachineId4ParallelId(parallel_id)); int64_t thrd_id = -1; if (pd.device_type() == DeviceType::kCPU) { thrd_id = Global<IDMgr>::Get()->PickCpuThrdIdEvenly(machine_id); } else if (pd.device_type() == DeviceType::kGPU) { #ifdef WITH_CUDA int64_t dev_id = CHECK_JUST(pd.DeviceId4ParallelId(parallel_id)); thrd_id = GetBoxingGpuThrdId(machine_id, dev_id, CudaWorkType::kCopyH2D); #else UNIMPLEMENTED(); #endif } else { UNIMPLEMENTED(); } node->Init(lbi, slice, mode, machine_id, thrd_id); return node; }; const auto CreateBoxingNodeToHost = [&ctx, &lbi, &GetBoxingGpuThrdId, &NewEdge]( TaskNode* src_node, const TensorSliceView& src_slice, const TensorSliceView& dst_slice) -> SliceBoxingTaskNode* { SliceBoxingTaskNode* dst_node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>(); int64_t thrd_id = -1; if (src_node->device_type() == DeviceType::kCPU) { thrd_id = Global<IDMgr>::Get()->PickCpuThrdIdEvenly(src_node->machine_id()); } else if (src_node->device_type() == DeviceType::kGPU) { #ifdef WITH_CUDA thrd_id = GetBoxingGpuThrdId(src_node->machine_id(), src_node->GpuPhyId(), CudaWorkType::kCopyD2H); #else UNIMPLEMENTED(); #endif } else { UNIMPLEMENTED(); } dst_node->Init(lbi, dst_slice, kSliceBoxingTaskModeCopy, src_node->machine_id(), thrd_id, Global<IDMgr>::Get()->CpuMemZoneId()); dst_node->ConnectToSrcNodeWithSlice(src_node, NewEdge(), src_slice); return dst_node; }; const auto BuildSubTaskGphS2B = [&ctx, &CreateBoxingNode121, &NewEdge, &lbi]( const ParallelDesc& in_pd, const ParallelDesc& out_pd, const SbpParallel& in_sbp, const SbpParallel& out_sbp, const BlobDesc& blob_desc, const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) { CHECK(SubTskGphBuilderUtil::IsBoxingS2B(in_sbp, out_sbp)); const std::vector<TensorSliceView> in_slices = GetTensorSliceView(in_pd.parallel_num(), in_sbp, blob_desc); CHECK(!ContainsEmptySlice(in_slices)); const TensorSliceView out_slice = GetBroadcastTensorSliceView(blob_desc); FOR_RANGE(int64_t, out_id, 0, out_pd.parallel_num()) { SliceBoxingTaskNode* out_node = CreateBoxingNode121(out_pd, out_id, out_slice, kSliceBoxingTaskModeCopy); FOR_RANGE(int64_t, in_id, 0, in_pd.parallel_num()) { const TensorSliceView& in_slice = in_slices.at(in_id); TaskNode* in_node = in_nodes.at(in_id); if (SubTskGphBuilderUtil::IsOnSameGPU(in_node, out_node)) { out_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice); } else { TaskNode* proxy_node = ctx->task_graph()->GetProxyNode( in_node, lbi, out_node->machine_id(), Global<IDMgr>::Get()->CpuMemZoneId()); out_node->ConnectToSrcNodeWithSlice(proxy_node, NewEdge(), in_slice); } } out_nodes->push_back(out_node); } }; const auto BuildSubTaskGphS2S = [&ctx, &lbi, &CreateBoxingNode121, &CreateBoxingNodeToHost, &GetBoxingGpuThrdId, &NewEdge](const ParallelDesc& in_pd, const ParallelDesc& out_pd, const SbpParallel& in_sbp, const SbpParallel& out_sbp, const BlobDesc& blob_desc, const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) { CHECK(SubTskGphBuilderUtil::IsBoxingS2S(in_sbp, out_sbp)); const std::vector<TensorSliceView> in_slices = GetTensorSliceView(in_pd.parallel_num(), in_sbp, blob_desc); CHECK(!ContainsEmptySlice(in_slices)); const std::vector<TensorSliceView> out_slices = GetTensorSliceView(out_pd.parallel_num(), out_sbp, blob_desc); CHECK(!ContainsEmptySlice(out_slices)); HashMap<int64_t, std::vector<int64_t>> machine_id2in_parallel_ids; GroupParallelIdByMachine(in_pd, &machine_id2in_parallel_ids); FOR_RANGE(int64_t, out_id, 0, out_pd.parallel_num()) { const TensorSliceView& out_slice = out_slices.at(out_id); SliceBoxingTaskNode* out_node = CreateBoxingNode121(out_pd, out_id, out_slice, kSliceBoxingTaskModeCopy); for (const auto& pair : machine_id2in_parallel_ids) { const int64_t in_machine_id = pair.first; const std::vector<int64_t>& in_parallel_ids = pair.second; if (out_node->machine_id() == in_machine_id) { for (const int64_t in_id : in_parallel_ids) { const TensorSliceView& in_slice = in_slices.at(in_id); const TensorSliceView& intersection = out_slice.Intersect(in_slice); if (intersection.IsEmpty()) { continue; } TaskNode* in_node = in_nodes.at(in_id); if (in_pd.device_type() == DeviceType::kGPU && out_pd.device_type() == DeviceType::kCPU) { SliceBoxingTaskNode* copy_to_host = CreateBoxingNodeToHost(in_node, in_slice, intersection); out_node->ConnectToSrcNodeWithSlice(copy_to_host, NewEdge(), intersection); } else if (in_pd.device_type() == DeviceType::kCPU && out_pd.device_type() == DeviceType::kCPU) { out_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice); } else { bool in_contiguous = IsCopyContiguous(in_slice, intersection); bool out_contiguous = IsCopyContiguous(intersection, out_slice); if (IsSameDevice(in_pd, out_pd, in_id, out_id) || (in_contiguous && out_contiguous)) { out_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice); } else if (in_contiguous && !out_contiguous) { SliceBoxingTaskNode* copy_to_out_continuous = CreateBoxingNode121(out_pd, out_id, intersection, kSliceBoxingTaskModeCopy); copy_to_out_continuous->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice); out_node->ConnectToSrcNodeWithSlice(copy_to_out_continuous, NewEdge(), intersection); } else if (!in_contiguous && out_contiguous) { SliceBoxingTaskNode* in_copy_to_continuous = CreateBoxingNode121(in_pd, in_id, intersection, kSliceBoxingTaskModeCopy); in_copy_to_continuous->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice); out_node->ConnectToSrcNodeWithSlice(in_copy_to_continuous, NewEdge(), intersection); } else { SliceBoxingTaskNode* in_copy_to_continuous = CreateBoxingNode121(in_pd, in_id, intersection, kSliceBoxingTaskModeCopy); in_copy_to_continuous->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice); SliceBoxingTaskNode* copy_to_out_continuous = CreateBoxingNode121(out_pd, out_id, intersection, kSliceBoxingTaskModeCopy); copy_to_out_continuous->ConnectToSrcNodeWithSlice(in_copy_to_continuous, NewEdge(), intersection); out_node->ConnectToSrcNodeWithSlice(copy_to_out_continuous, NewEdge(), intersection); } } } } else { HashMap<int64_t, TensorSliceView> in_id2intersection; std::vector<TensorSliceView> non_empty_intersections; for (const int64_t in_id : in_parallel_ids) { const TensorSliceView& intersection = out_slice.Intersect(in_slices.at(in_id)); in_id2intersection[in_id] = intersection; if (!intersection.IsEmpty()) { non_empty_intersections.push_back(intersection); } } if (non_empty_intersections.empty()) { continue; } const TensorSliceView concat_slice = TensorSliceView::Concatenate(non_empty_intersections, in_sbp.split_parallel().axis()); SliceBoxingTaskNode* local_concat_node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>(); int64_t local_concat_thrd_id = -1; if (in_pd.device_type() == DeviceType::kCPU) { local_concat_thrd_id = Global<IDMgr>::Get()->PickCpuThrdIdEvenly(in_machine_id); } else if (in_pd.device_type() == DeviceType::kGPU) { #ifdef WITH_CUDA TaskNode* node = in_nodes.at(in_parallel_ids.at(out_id % in_parallel_ids.size())); local_concat_thrd_id = GetBoxingGpuThrdId(node->machine_id(), node->GpuPhyId(), CudaWorkType::kCopyD2H); #else UNIMPLEMENTED(); #endif } local_concat_node->Init(lbi, concat_slice, kSliceBoxingTaskModeCopy, in_machine_id, local_concat_thrd_id, Global<IDMgr>::Get()->CpuMemZoneId()); for (const int64_t in_id : in_parallel_ids) { if (!in_id2intersection.at(in_id).IsEmpty()) { local_concat_node->ConnectToSrcNodeWithSlice(in_nodes.at(in_id), NewEdge(), in_slices.at(in_id)); } } TaskNode* local_add_proxy_node = ctx->task_graph()->GetProxyNode( local_concat_node, lbi, out_node->machine_id(), Global<IDMgr>::Get()->CpuMemZoneId()); out_node->ConnectToSrcNodeWithSlice(local_add_proxy_node, NewEdge(), concat_slice); } } out_nodes->push_back(out_node); } }; const auto BuildSubTaskGphP2S = [&ctx, &lbi, &CreateBoxingNode121, &CreateBoxingNodeToHost, &GetBoxingGpuThrdId, &NewEdge](const ParallelDesc& in_pd, const ParallelDesc& out_pd, const SbpParallel& in_sbp, const SbpParallel& out_sbp, const BlobDesc& blob_desc, const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) { CHECK(SubTskGphBuilderUtil::IsBoxingP2S(in_sbp, out_sbp)); const TensorSliceView in_slice = GetBroadcastTensorSliceView(blob_desc); const std::vector<TensorSliceView> out_slices = GetTensorSliceView(out_pd.parallel_num(), out_sbp, blob_desc); CHECK(!ContainsEmptySlice(out_slices)); HashMap<int64_t, std::vector<int64_t>> machine_id2in_parallel_ids; GroupParallelIdByMachine(in_pd, &machine_id2in_parallel_ids); FOR_RANGE(int64_t, out_id, 0, out_pd.parallel_num()) { const TensorSliceView& out_slice = out_slices.at(out_id); SliceBoxingTaskNode* out_node = CreateBoxingNode121(out_pd, out_id, out_slice, kSliceBoxingTaskModeAdd); for (const auto& pair : machine_id2in_parallel_ids) { const int64_t in_machine_id = pair.first; const std::vector<int64_t>& in_parallel_ids = pair.second; if (out_node->machine_id() == in_machine_id) { for (const int64_t in_id : in_parallel_ids) { TaskNode* in_node = in_nodes.at(in_id); if (SubTskGphBuilderUtil::IsOnSameGPU(in_node, out_node)) { out_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice); } else if (in_pd.device_type() == DeviceType::kGPU) { SliceBoxingTaskNode* copy_to_host = CreateBoxingNodeToHost(in_node, in_slice, out_slice); out_node->ConnectToSrcNodeWithSlice(copy_to_host, NewEdge(), out_slice); } else { out_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice); } } } else { auto* local_add_node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>(); int64_t local_add_thrd_id = -1; if (in_pd.device_type() == DeviceType::kCPU) { local_add_thrd_id = Global<IDMgr>::Get()->PickCpuThrdIdEvenly(in_machine_id); } else if (in_pd.device_type() == DeviceType::kGPU) { #ifdef WITH_CUDA TaskNode* node = in_nodes.at(in_parallel_ids.at(out_id % in_parallel_ids.size())); local_add_thrd_id = GetBoxingGpuThrdId(node->machine_id(), node->GpuPhyId(), CudaWorkType::kCopyD2H); #else UNIMPLEMENTED(); #endif } local_add_node->Init(lbi, out_slice, kSliceBoxingTaskModeAdd, in_machine_id, local_add_thrd_id, Global<IDMgr>::Get()->CpuMemZoneId()); for (const int64_t in_id : in_parallel_ids) { local_add_node->ConnectToSrcNodeWithSlice(in_nodes.at(in_id), NewEdge(), in_slice); } TaskNode* local_add_proxy_node = ctx->task_graph()->GetProxyNode( local_add_node, lbi, out_node->machine_id(), Global<IDMgr>::Get()->CpuMemZoneId()); out_node->ConnectToSrcNodeWithSlice(local_add_proxy_node, NewEdge(), out_slice); } } out_nodes->push_back(out_node); } }; const auto BuildSubTaskGphP2B = [&ctx, &lbi, &GetBoxingGpuThrdId, &NewEdge]( const ParallelDesc& in_pd, const ParallelDesc& out_pd, const SbpParallel& in_sbp, const SbpParallel& out_sbp, const BlobDesc& blob_desc, const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) { CHECK(SubTskGphBuilderUtil::IsBoxingP2B(in_sbp, out_sbp)); const TensorSliceView slice = GetBroadcastTensorSliceView(blob_desc); HashMap<int64_t, std::vector<int64_t>> machine_id2in_parallel_ids; HashMap<int64_t, std::vector<int64_t>> machine_id2out_parallel_ids; GroupParallelIdByMachine(in_pd, &machine_id2in_parallel_ids); GroupParallelIdByMachine(out_pd, &machine_id2out_parallel_ids); std::vector<TaskNode*> out_box_nodes; for (const auto& machine_id7in_parallel_ids : machine_id2in_parallel_ids) { const int64_t in_machine_id = machine_id7in_parallel_ids.first; const std::vector<int64_t>& in_ids_on_machine = machine_id7in_parallel_ids.second; if (in_ids_on_machine.size() == 1) { out_box_nodes.push_back(in_nodes.at(in_ids_on_machine.front())); } else { auto* local_add_node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>(); int64_t local_add_thrd_id = -1; if (in_pd.device_type() == DeviceType::kCPU) { local_add_thrd_id = Global<IDMgr>::Get()->PickCpuThrdIdEvenly(in_machine_id); } else if (in_pd.device_type() == DeviceType::kGPU) { #ifdef WITH_CUDA TaskNode* node = in_nodes.at(in_ids_on_machine.front()); local_add_thrd_id = GetBoxingGpuThrdId(node->machine_id(), node->GpuPhyId(), CudaWorkType::kCopyH2D); #else UNIMPLEMENTED(); #endif } local_add_node->Init(lbi, slice, kSliceBoxingTaskModeAdd, in_machine_id, local_add_thrd_id); FOR_RANGE(int64_t, i, 0, in_ids_on_machine.size()) { local_add_node->ConnectToSrcNodeWithSlice(in_nodes.at(in_ids_on_machine.at(i)), NewEdge(), slice); } out_box_nodes.push_back(local_add_node); } } out_nodes->resize(out_pd.parallel_num()); for (const auto& machine_id7out_parallel_ids : machine_id2out_parallel_ids) { const int64_t out_machine_id = machine_id7out_parallel_ids.first; TaskNode* in_box_node = nullptr; if (out_box_nodes.size() == 1) { in_box_node = ctx->task_graph()->GetProxyNode(out_box_nodes.front(), lbi, machine_id7out_parallel_ids.first, Global<IDMgr>::Get()->CpuMemZoneId()); } else { auto* add_node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>(); add_node->Init(lbi, slice, kSliceBoxingTaskModeAdd, machine_id7out_parallel_ids.first, Global<IDMgr>::Get()->PickCpuThrdIdEvenly(machine_id7out_parallel_ids.first), Global<IDMgr>::Get()->CpuMemZoneId()); for (TaskNode* out_box_node : out_box_nodes) { TaskNode* out_boxing_node_proxy = ctx->task_graph()->GetProxyNode( out_box_node, lbi, out_machine_id, Global<IDMgr>::Get()->CpuMemZoneId()); add_node->ConnectToSrcNodeWithSlice(out_boxing_node_proxy, NewEdge(), slice); } in_box_node = add_node; } for (const int64_t out_id : machine_id7out_parallel_ids.second) { int64_t mem_zone_id; if (out_pd.device_type() == DeviceType::kCPU) { mem_zone_id = Global<IDMgr>::Get()->CpuMemZoneId(); } else if (out_pd.device_type() == DeviceType::kGPU) { mem_zone_id = Global<IDMgr>::Get()->GpuMemZoneId(CHECK_JUST(out_pd.DeviceId4ParallelId(out_id))); } else { UNIMPLEMENTED(); } (*out_nodes)[out_id] = ctx->task_graph()->GetProxyNode(in_box_node, lbi, out_machine_id, mem_zone_id); } } }; const auto BuildSubTaskGphB2S = [&ctx, &lbi, &CreateBoxingNode121, &CreateBoxingNodeToHost, &GetBoxingGpuThrdId, &NewEdge]( const ParallelDesc& in_pd, const ParallelDesc& out_pd, const SbpParallel& in_sbp, const SbpParallel& out_sbp, const BlobDesc& blob_desc, const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) { CHECK(SubTskGphBuilderUtil::IsBoxingB2S(in_sbp, out_sbp)); const TensorSliceView in_slice = GetBroadcastTensorSliceView(blob_desc); const std::vector<TensorSliceView> out_slices = GetTensorSliceView(out_pd.parallel_num(), out_sbp, blob_desc); CHECK(!ContainsEmptySlice(out_slices)); FOR_RANGE(int64_t, out_id, 0, out_pd.parallel_num()) { const TensorSliceView& out_slice = out_slices.at(out_id); const int64_t nearest_idx = SubTskGphBuilderUtil::FindNearestSrcParallelId(in_pd, out_pd, out_id); TaskNode* in_node = in_nodes.at(nearest_idx); SliceBoxingTaskNode* slice_node = CreateBoxingNode121(in_pd, nearest_idx, out_slice, kSliceBoxingTaskModeCopy); slice_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice); TaskNode* out_node = ctx->task_graph()->GetProxyNode(slice_node, lbi, out_pd, out_id); out_nodes->push_back(out_node); } }; std::string comment; if (SubTskGphBuilderUtil::IsBoxingS2B(in_sbp_parallel, out_sbp_parallel)) { BuildSubTaskGphS2B(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel, logical_blob_desc, sorted_in_tasks, sorted_out_tasks); comment = "BuildSubTaskGphS2B"; } else if (SubTskGphBuilderUtil::IsBoxingS2S(in_sbp_parallel, out_sbp_parallel)) { BuildSubTaskGphS2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel, logical_blob_desc, sorted_in_tasks, sorted_out_tasks); comment = "BuildSubTaskGphS2S"; } else if (SubTskGphBuilderUtil::IsBoxingP2S(in_sbp_parallel, out_sbp_parallel)) { BuildSubTaskGphP2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel, logical_blob_desc, sorted_in_tasks, sorted_out_tasks); comment = "BuildSubTaskGphP2S"; } else if (SubTskGphBuilderUtil::IsBoxingP2B(in_sbp_parallel, out_sbp_parallel)) { if (logical_blob_desc.shape().elem_cnt() < out_parallel_desc.parallel_num()) { BuildSubTaskGphP2B(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel, logical_blob_desc, sorted_in_tasks, sorted_out_tasks); comment = "BuildSubTaskGphP2B"; } else { BlobDesc flat_blob_desc(logical_blob_desc.data_type()); flat_blob_desc.mut_shape() = Shape({logical_blob_desc.shape().elem_cnt()}); std::vector<TaskNode*> middle_nodes; SbpParallel middle_sbp; middle_sbp.mutable_split_parallel()->set_axis(0); BuildSubTaskGphP2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, middle_sbp, flat_blob_desc, sorted_in_tasks, &middle_nodes); BuildSubTaskGphS2B(out_parallel_desc, out_parallel_desc, middle_sbp, out_sbp_parallel, flat_blob_desc, middle_nodes, sorted_out_tasks); comment = "BuildSubTaskGphP2S->BuildSubTaskGphS2B"; for (TaskNode* out_node : *sorted_out_tasks) { auto* slice_boxing_node = dynamic_cast<SliceBoxingTaskNode*>(out_node); CHECK_NOTNULL(slice_boxing_node); slice_boxing_node->SetOutShape(logical_blob_desc.shape()); } } } else if (SubTskGphBuilderUtil::IsBoxingB2S(in_sbp_parallel, out_sbp_parallel)) { BuildSubTaskGphB2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel, logical_blob_desc, sorted_in_tasks, sorted_out_tasks); comment = "BuildSubTaskGphB2S"; } else { UNIMPLEMENTED(); } return TRY(BuildSubTskGphBuilderStatus("SliceBoxingSubTskGphBuilder", comment)); } } // namespace oneflow
; A282513: a(n) = floor((3*n + 2)^2/24 + 1/3). ; 0,1,3,5,8,12,17,22,28,35,43,51,60,70,81,92,104,117,131,145,160,176,193,210,228,247,267,287,308,330,353,376,400,425,451,477,504,532,561,590,620,651,683,715,748,782,817,852,888,925,963 mov $2,$0 add $2,2 lpb $0,1 trn $1,$2 add $1,$0 sub $0,1 trn $2,4 lpe
; A169451: Number of reduced words of length n in Coxeter group on 6 generators S_i with relations (S_i)^2 = (S_i S_j)^33 = I. ; 1,6,30,150,750,3750,18750,93750,468750,2343750,11718750,58593750,292968750,1464843750,7324218750,36621093750,183105468750,915527343750,4577636718750,22888183593750,114440917968750,572204589843750 mov $1,5 pow $1,$0 mul $1,6 div $1,5 mov $0,$1
;Testname=noerr; Arguments=-felf64 -ogotoff64.o; Files=stdout stderr gotoff64.o ;Testname=err; Arguments=-DERROR -felf64 -ogotoff64.o; Files=stdout stderr gotoff64.o bits 64 default rel extern foo mov r15,[foo wrt ..got] lea r12,[foo wrt ..got] %ifdef ERROR lea rax,[foo wrt ..gotoff] mov rax,[foo wrt ..gotoff] %endif default abs mov r15,[foo wrt ..got] lea r12,[foo wrt ..got] mov rax,[qword foo wrt ..got] %ifdef ERROR lea rax,[foo wrt ..gotoff] mov rax,[foo wrt ..gotoff] %endif mov rax,[qword foo wrt ..gotoff]
ScoopDebrisOffset equ 0 ; hull byte#0 high nibble is scoop info, lower nibble is debris spin info MissileLockLoOffset equ 1 MissileLockHiOffset equ 2 EdgeAddyOffset equ 3 LineX4Offset equ 5 GunVertexOffset equ 6 ExplosionCtOffset equ 7 VertexCtX6Offset equ 8 EdgeCountOffset equ 9 BountyLoOffset equ 10 BountyHiOffset equ 11 FaceCtX4Offset equ 12 DotOffset equ 13 EnergyOffset equ 14 SpeedOffset equ 15 FaceAddyOffset equ 16 QOffset equ 18 LaserOffset equ 19 VerticiesAddyOffset equ 20 ShipTypeOffset equ 22 ShipNewBitsOffset equ 23 ShipDataLength equ ShipNewBitsOffset+1 CobraTablePointer equ 43 ;29 faulty BankThreshold equ 16 ShipTableALast equ 23 ShipTableBLast equ 39 ShipTableCLast equ 55
//===-- sancov.cpp --------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // This file is a command-line tool for reading and analyzing sanitizer // coverage. //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" #include "llvm/DebugInfo/Symbolize/Symbolize.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCDisassembler/MCDisassembler.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstrAnalysis.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCTargetOptions.h" #include "llvm/Object/Archive.h" #include "llvm/Object/Binary.h" #include "llvm/Object/COFF.h" #include "llvm/Object/MachO.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Errc.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/JSON.h" #include "llvm/Support/MD5.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Regex.h" #include "llvm/Support/SHA1.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/SpecialCaseList.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/YAMLParser.h" #include "llvm/Support/raw_ostream.h" #include <set> #include <vector> using namespace llvm; namespace { // --------- COMMAND LINE FLAGS --------- enum ActionType { CoveredFunctionsAction, HtmlReportAction, MergeAction, NotCoveredFunctionsAction, PrintAction, PrintCovPointsAction, StatsAction, SymbolizeAction }; cl::opt<ActionType> Action( cl::desc("Action (required)"), cl::Required, cl::values( clEnumValN(PrintAction, "print", "Print coverage addresses"), clEnumValN(PrintCovPointsAction, "print-coverage-pcs", "Print coverage instrumentation points addresses."), clEnumValN(CoveredFunctionsAction, "covered-functions", "Print all covered funcions."), clEnumValN(NotCoveredFunctionsAction, "not-covered-functions", "Print all not covered funcions."), clEnumValN(StatsAction, "print-coverage-stats", "Print coverage statistics."), clEnumValN(HtmlReportAction, "html-report", "REMOVED. Use -symbolize & coverage-report-server.py."), clEnumValN(SymbolizeAction, "symbolize", "Produces a symbolized JSON report from binary report."), clEnumValN(MergeAction, "merge", "Merges reports."))); static cl::list<std::string> ClInputFiles(cl::Positional, cl::OneOrMore, cl::desc("<action> <binary files...> <.sancov files...> " "<.symcov files...>")); static cl::opt<bool> ClDemangle("demangle", cl::init(true), cl::desc("Print demangled function name.")); static cl::opt<bool> ClSkipDeadFiles("skip-dead-files", cl::init(true), cl::desc("Do not list dead source files in reports.")); static cl::opt<std::string> ClStripPathPrefix( "strip_path_prefix", cl::init(""), cl::desc("Strip this prefix from file paths in reports.")); static cl::opt<std::string> ClBlacklist("blacklist", cl::init(""), cl::desc("Blacklist file (sanitizer blacklist format).")); static cl::opt<bool> ClUseDefaultBlacklist( "use_default_blacklist", cl::init(true), cl::Hidden, cl::desc("Controls if default blacklist should be used.")); static const char *const DefaultBlacklistStr = "fun:__sanitizer_.*\n" "src:/usr/include/.*\n" "src:.*/libc\\+\\+/.*\n"; // --------- FORMAT SPECIFICATION --------- struct FileHeader { uint32_t Bitness; uint32_t Magic; }; static const uint32_t BinCoverageMagic = 0xC0BFFFFF; static const uint32_t Bitness32 = 0xFFFFFF32; static const uint32_t Bitness64 = 0xFFFFFF64; static const Regex SancovFileRegex("(.*)\\.[0-9]+\\.sancov"); static const Regex SymcovFileRegex(".*\\.symcov"); // --------- MAIN DATASTRUCTURES ---------- // Contents of .sancov file: list of coverage point addresses that were // executed. struct RawCoverage { explicit RawCoverage(std::unique_ptr<std::set<uint64_t>> Addrs) : Addrs(std::move(Addrs)) {} // Read binary .sancov file. static ErrorOr<std::unique_ptr<RawCoverage>> read(const std::string &FileName); std::unique_ptr<std::set<uint64_t>> Addrs; }; // Coverage point has an opaque Id and corresponds to multiple source locations. struct CoveragePoint { explicit CoveragePoint(const std::string &Id) : Id(Id) {} std::string Id; SmallVector<DILineInfo, 1> Locs; }; // Symcov file content: set of covered Ids plus information about all available // coverage points. struct SymbolizedCoverage { // Read json .symcov file. static std::unique_ptr<SymbolizedCoverage> read(const std::string &InputFile); std::set<std::string> CoveredIds; std::string BinaryHash; std::vector<CoveragePoint> Points; }; struct CoverageStats { size_t AllPoints; size_t CovPoints; size_t AllFns; size_t CovFns; }; // --------- ERROR HANDLING --------- static void fail(const llvm::Twine &E) { errs() << "ERROR: " << E << "\n"; exit(1); } static void failIf(bool B, const llvm::Twine &E) { if (B) fail(E); } static void failIfError(std::error_code Error) { if (!Error) return; errs() << "ERROR: " << Error.message() << "(" << Error.value() << ")\n"; exit(1); } template <typename T> static void failIfError(const ErrorOr<T> &E) { failIfError(E.getError()); } static void failIfError(Error Err) { if (Err) { logAllUnhandledErrors(std::move(Err), errs(), "ERROR: "); exit(1); } } template <typename T> static void failIfError(Expected<T> &E) { failIfError(E.takeError()); } static void failIfNotEmpty(const llvm::Twine &E) { if (E.str().empty()) return; fail(E); } template <typename T> static void failIfEmpty(const std::unique_ptr<T> &Ptr, const std::string &Message) { if (Ptr.get()) return; fail(Message); } // ----------- Coverage I/O ---------- template <typename T> static void readInts(const char *Start, const char *End, std::set<uint64_t> *Ints) { const T *S = reinterpret_cast<const T *>(Start); const T *E = reinterpret_cast<const T *>(End); std::copy(S, E, std::inserter(*Ints, Ints->end())); } ErrorOr<std::unique_ptr<RawCoverage>> RawCoverage::read(const std::string &FileName) { ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(FileName); if (!BufOrErr) return BufOrErr.getError(); std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get()); if (Buf->getBufferSize() < 8) { errs() << "File too small (<8): " << Buf->getBufferSize() << '\n'; return make_error_code(errc::illegal_byte_sequence); } const FileHeader *Header = reinterpret_cast<const FileHeader *>(Buf->getBufferStart()); if (Header->Magic != BinCoverageMagic) { errs() << "Wrong magic: " << Header->Magic << '\n'; return make_error_code(errc::illegal_byte_sequence); } auto Addrs = std::make_unique<std::set<uint64_t>>(); switch (Header->Bitness) { case Bitness64: readInts<uint64_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(), Addrs.get()); break; case Bitness32: readInts<uint32_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(), Addrs.get()); break; default: errs() << "Unsupported bitness: " << Header->Bitness << '\n'; return make_error_code(errc::illegal_byte_sequence); } // Ignore slots that are zero, so a runtime implementation is not required // to compactify the data. Addrs->erase(0); return std::unique_ptr<RawCoverage>(new RawCoverage(std::move(Addrs))); } // Print coverage addresses. raw_ostream &operator<<(raw_ostream &OS, const RawCoverage &CoverageData) { for (auto Addr : *CoverageData.Addrs) { OS << "0x"; OS.write_hex(Addr); OS << "\n"; } return OS; } static raw_ostream &operator<<(raw_ostream &OS, const CoverageStats &Stats) { OS << "all-edges: " << Stats.AllPoints << "\n"; OS << "cov-edges: " << Stats.CovPoints << "\n"; OS << "all-functions: " << Stats.AllFns << "\n"; OS << "cov-functions: " << Stats.CovFns << "\n"; return OS; } // Output symbolized information for coverage points in JSON. // Format: // { // '<file_name>' : { // '<function_name>' : { // '<point_id'> : '<line_number>:'<column_number'. // .... // } // } // } static void operator<<(json::OStream &W, const std::vector<CoveragePoint> &Points) { // Group points by file. std::map<std::string, std::vector<const CoveragePoint *>> PointsByFile; for (const auto &Point : Points) { for (const DILineInfo &Loc : Point.Locs) { PointsByFile[Loc.FileName].push_back(&Point); } } for (const auto &P : PointsByFile) { std::string FileName = P.first; std::map<std::string, std::vector<const CoveragePoint *>> PointsByFn; for (auto PointPtr : P.second) { for (const DILineInfo &Loc : PointPtr->Locs) { PointsByFn[Loc.FunctionName].push_back(PointPtr); } } W.attributeObject(P.first, [&] { // Group points by function. for (const auto &P : PointsByFn) { std::string FunctionName = P.first; std::set<std::string> WrittenIds; W.attributeObject(FunctionName, [&] { for (const CoveragePoint *Point : P.second) { for (const auto &Loc : Point->Locs) { if (Loc.FileName != FileName || Loc.FunctionName != FunctionName) continue; if (WrittenIds.find(Point->Id) != WrittenIds.end()) continue; // Output <point_id> : "<line>:<col>". WrittenIds.insert(Point->Id); W.attribute(Point->Id, (utostr(Loc.Line) + ":" + utostr(Loc.Column))); } } }); } }); } } static void operator<<(json::OStream &W, const SymbolizedCoverage &C) { W.object([&] { W.attributeArray("covered-points", [&] { for (const std::string &P : C.CoveredIds) { W.value(P); } }); W.attribute("binary-hash", C.BinaryHash); W.attributeObject("point-symbol-info", [&] { W << C.Points; }); }); } static std::string parseScalarString(yaml::Node *N) { SmallString<64> StringStorage; yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N); failIf(!S, "expected string"); return std::string(S->getValue(StringStorage)); } std::unique_ptr<SymbolizedCoverage> SymbolizedCoverage::read(const std::string &InputFile) { auto Coverage(std::make_unique<SymbolizedCoverage>()); std::map<std::string, CoveragePoint> Points; ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(InputFile); failIfError(BufOrErr); SourceMgr SM; yaml::Stream S(**BufOrErr, SM); yaml::document_iterator DI = S.begin(); failIf(DI == S.end(), "empty document: " + InputFile); yaml::Node *Root = DI->getRoot(); failIf(!Root, "expecting root node: " + InputFile); yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root); failIf(!Top, "expecting mapping node: " + InputFile); for (auto &KVNode : *Top) { auto Key = parseScalarString(KVNode.getKey()); if (Key == "covered-points") { yaml::SequenceNode *Points = dyn_cast<yaml::SequenceNode>(KVNode.getValue()); failIf(!Points, "expected array: " + InputFile); for (auto I = Points->begin(), E = Points->end(); I != E; ++I) { Coverage->CoveredIds.insert(parseScalarString(&*I)); } } else if (Key == "binary-hash") { Coverage->BinaryHash = parseScalarString(KVNode.getValue()); } else if (Key == "point-symbol-info") { yaml::MappingNode *PointSymbolInfo = dyn_cast<yaml::MappingNode>(KVNode.getValue()); failIf(!PointSymbolInfo, "expected mapping node: " + InputFile); for (auto &FileKVNode : *PointSymbolInfo) { auto Filename = parseScalarString(FileKVNode.getKey()); yaml::MappingNode *FileInfo = dyn_cast<yaml::MappingNode>(FileKVNode.getValue()); failIf(!FileInfo, "expected mapping node: " + InputFile); for (auto &FunctionKVNode : *FileInfo) { auto FunctionName = parseScalarString(FunctionKVNode.getKey()); yaml::MappingNode *FunctionInfo = dyn_cast<yaml::MappingNode>(FunctionKVNode.getValue()); failIf(!FunctionInfo, "expected mapping node: " + InputFile); for (auto &PointKVNode : *FunctionInfo) { auto PointId = parseScalarString(PointKVNode.getKey()); auto Loc = parseScalarString(PointKVNode.getValue()); size_t ColonPos = Loc.find(':'); failIf(ColonPos == std::string::npos, "expected ':': " + InputFile); auto LineStr = Loc.substr(0, ColonPos); auto ColStr = Loc.substr(ColonPos + 1, Loc.size()); if (Points.find(PointId) == Points.end()) Points.insert(std::make_pair(PointId, CoveragePoint(PointId))); DILineInfo LineInfo; LineInfo.FileName = Filename; LineInfo.FunctionName = FunctionName; char *End; LineInfo.Line = std::strtoul(LineStr.c_str(), &End, 10); LineInfo.Column = std::strtoul(ColStr.c_str(), &End, 10); CoveragePoint *CoveragePoint = &Points.find(PointId)->second; CoveragePoint->Locs.push_back(LineInfo); } } } } else { errs() << "Ignoring unknown key: " << Key << "\n"; } } for (auto &KV : Points) { Coverage->Points.push_back(KV.second); } return Coverage; } // ---------- MAIN FUNCTIONALITY ---------- std::string stripPathPrefix(std::string Path) { if (ClStripPathPrefix.empty()) return Path; size_t Pos = Path.find(ClStripPathPrefix); if (Pos == std::string::npos) return Path; return Path.substr(Pos + ClStripPathPrefix.size()); } static std::unique_ptr<symbolize::LLVMSymbolizer> createSymbolizer() { symbolize::LLVMSymbolizer::Options SymbolizerOptions; SymbolizerOptions.Demangle = ClDemangle; SymbolizerOptions.UseSymbolTable = true; return std::unique_ptr<symbolize::LLVMSymbolizer>( new symbolize::LLVMSymbolizer(SymbolizerOptions)); } static std::string normalizeFilename(const std::string &FileName) { SmallString<256> S(FileName); sys::path::remove_dots(S, /* remove_dot_dot */ true); return stripPathPrefix(std::string(S)); } class Blacklists { public: Blacklists() : DefaultBlacklist(createDefaultBlacklist()), UserBlacklist(createUserBlacklist()) {} bool isBlacklisted(const DILineInfo &I) { if (DefaultBlacklist && DefaultBlacklist->inSection("sancov", "fun", I.FunctionName)) return true; if (DefaultBlacklist && DefaultBlacklist->inSection("sancov", "src", I.FileName)) return true; if (UserBlacklist && UserBlacklist->inSection("sancov", "fun", I.FunctionName)) return true; if (UserBlacklist && UserBlacklist->inSection("sancov", "src", I.FileName)) return true; return false; } private: static std::unique_ptr<SpecialCaseList> createDefaultBlacklist() { if (!ClUseDefaultBlacklist) return std::unique_ptr<SpecialCaseList>(); std::unique_ptr<MemoryBuffer> MB = MemoryBuffer::getMemBuffer(DefaultBlacklistStr); std::string Error; auto Blacklist = SpecialCaseList::create(MB.get(), Error); failIfNotEmpty(Error); return Blacklist; } static std::unique_ptr<SpecialCaseList> createUserBlacklist() { if (ClBlacklist.empty()) return std::unique_ptr<SpecialCaseList>(); return SpecialCaseList::createOrDie({{ClBlacklist}}, *vfs::getRealFileSystem()); } std::unique_ptr<SpecialCaseList> DefaultBlacklist; std::unique_ptr<SpecialCaseList> UserBlacklist; }; static std::vector<CoveragePoint> getCoveragePoints(const std::string &ObjectFile, const std::set<uint64_t> &Addrs, const std::set<uint64_t> &CoveredAddrs) { std::vector<CoveragePoint> Result; auto Symbolizer(createSymbolizer()); Blacklists B; std::set<std::string> CoveredFiles; if (ClSkipDeadFiles) { for (auto Addr : CoveredAddrs) { // TODO: it would be neccessary to set proper section index here. // object::SectionedAddress::UndefSection works for only absolute // addresses. object::SectionedAddress ModuleAddress = { Addr, object::SectionedAddress::UndefSection}; auto LineInfo = Symbolizer->symbolizeCode(ObjectFile, ModuleAddress); failIfError(LineInfo); CoveredFiles.insert(LineInfo->FileName); auto InliningInfo = Symbolizer->symbolizeInlinedCode(ObjectFile, ModuleAddress); failIfError(InliningInfo); for (uint32_t I = 0; I < InliningInfo->getNumberOfFrames(); ++I) { auto FrameInfo = InliningInfo->getFrame(I); CoveredFiles.insert(FrameInfo.FileName); } } } for (auto Addr : Addrs) { std::set<DILineInfo> Infos; // deduplicate debug info. // TODO: it would be neccessary to set proper section index here. // object::SectionedAddress::UndefSection works for only absolute addresses. object::SectionedAddress ModuleAddress = { Addr, object::SectionedAddress::UndefSection}; auto LineInfo = Symbolizer->symbolizeCode(ObjectFile, ModuleAddress); failIfError(LineInfo); if (ClSkipDeadFiles && CoveredFiles.find(LineInfo->FileName) == CoveredFiles.end()) continue; LineInfo->FileName = normalizeFilename(LineInfo->FileName); if (B.isBlacklisted(*LineInfo)) continue; auto Id = utohexstr(Addr, true); auto Point = CoveragePoint(Id); Infos.insert(*LineInfo); Point.Locs.push_back(*LineInfo); auto InliningInfo = Symbolizer->symbolizeInlinedCode(ObjectFile, ModuleAddress); failIfError(InliningInfo); for (uint32_t I = 0; I < InliningInfo->getNumberOfFrames(); ++I) { auto FrameInfo = InliningInfo->getFrame(I); if (ClSkipDeadFiles && CoveredFiles.find(FrameInfo.FileName) == CoveredFiles.end()) continue; FrameInfo.FileName = normalizeFilename(FrameInfo.FileName); if (B.isBlacklisted(FrameInfo)) continue; if (Infos.find(FrameInfo) == Infos.end()) { Infos.insert(FrameInfo); Point.Locs.push_back(FrameInfo); } } Result.push_back(Point); } return Result; } static bool isCoveragePointSymbol(StringRef Name) { return Name == "__sanitizer_cov" || Name == "__sanitizer_cov_with_check" || Name == "__sanitizer_cov_trace_func_enter" || Name == "__sanitizer_cov_trace_pc_guard" || // Mac has '___' prefix Name == "___sanitizer_cov" || Name == "___sanitizer_cov_with_check" || Name == "___sanitizer_cov_trace_func_enter" || Name == "___sanitizer_cov_trace_pc_guard"; } // Locate __sanitizer_cov* function addresses inside the stubs table on MachO. static void findMachOIndirectCovFunctions(const object::MachOObjectFile &O, std::set<uint64_t> *Result) { MachO::dysymtab_command Dysymtab = O.getDysymtabLoadCommand(); MachO::symtab_command Symtab = O.getSymtabLoadCommand(); for (const auto &Load : O.load_commands()) { if (Load.C.cmd == MachO::LC_SEGMENT_64) { MachO::segment_command_64 Seg = O.getSegment64LoadCommand(Load); for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section_64 Sec = O.getSection64(Load, J); uint32_t SectionType = Sec.flags & MachO::SECTION_TYPE; if (SectionType == MachO::S_SYMBOL_STUBS) { uint32_t Stride = Sec.reserved2; uint32_t Cnt = Sec.size / Stride; uint32_t N = Sec.reserved1; for (uint32_t J = 0; J < Cnt && N + J < Dysymtab.nindirectsyms; J++) { uint32_t IndirectSymbol = O.getIndirectSymbolTableEntry(Dysymtab, N + J); uint64_t Addr = Sec.addr + J * Stride; if (IndirectSymbol < Symtab.nsyms) { object::SymbolRef Symbol = *(O.getSymbolByIndex(IndirectSymbol)); Expected<StringRef> Name = Symbol.getName(); failIfError(Name); if (isCoveragePointSymbol(Name.get())) { Result->insert(Addr); } } } } } } if (Load.C.cmd == MachO::LC_SEGMENT) { errs() << "ERROR: 32 bit MachO binaries not supported\n"; } } } // Locate __sanitizer_cov* function addresses that are used for coverage // reporting. static std::set<uint64_t> findSanitizerCovFunctions(const object::ObjectFile &O) { std::set<uint64_t> Result; for (const object::SymbolRef &Symbol : O.symbols()) { Expected<uint64_t> AddressOrErr = Symbol.getAddress(); failIfError(AddressOrErr); uint64_t Address = AddressOrErr.get(); Expected<StringRef> NameOrErr = Symbol.getName(); failIfError(NameOrErr); StringRef Name = NameOrErr.get(); if (!(Symbol.getFlags() & object::BasicSymbolRef::SF_Undefined) && isCoveragePointSymbol(Name)) { Result.insert(Address); } } if (const auto *CO = dyn_cast<object::COFFObjectFile>(&O)) { for (const object::ExportDirectoryEntryRef &Export : CO->export_directories()) { uint32_t RVA; std::error_code EC = Export.getExportRVA(RVA); failIfError(EC); StringRef Name; EC = Export.getSymbolName(Name); failIfError(EC); if (isCoveragePointSymbol(Name)) Result.insert(CO->getImageBase() + RVA); } } if (const auto *MO = dyn_cast<object::MachOObjectFile>(&O)) { findMachOIndirectCovFunctions(*MO, &Result); } return Result; } static uint64_t getPreviousInstructionPc(uint64_t PC, Triple TheTriple) { if (TheTriple.isARM()) { return (PC - 3) & (~1); } else if (TheTriple.isAArch64()) { return PC - 4; } else if (TheTriple.isMIPS()) { return PC - 8; } else { return PC - 1; } } // Locate addresses of all coverage points in a file. Coverage point // is defined as the 'address of instruction following __sanitizer_cov // call - 1'. static void getObjectCoveragePoints(const object::ObjectFile &O, std::set<uint64_t> *Addrs) { Triple TheTriple("unknown-unknown-unknown"); TheTriple.setArch(Triple::ArchType(O.getArch())); auto TripleName = TheTriple.getTriple(); std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); failIfNotEmpty(Error); std::unique_ptr<const MCSubtargetInfo> STI( TheTarget->createMCSubtargetInfo(TripleName, "", "")); failIfEmpty(STI, "no subtarget info for target " + TripleName); std::unique_ptr<const MCRegisterInfo> MRI( TheTarget->createMCRegInfo(TripleName)); failIfEmpty(MRI, "no register info for target " + TripleName); MCTargetOptions MCOptions; std::unique_ptr<const MCAsmInfo> AsmInfo( TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); failIfEmpty(AsmInfo, "no asm info for target " + TripleName); std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo); MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get()); std::unique_ptr<MCDisassembler> DisAsm( TheTarget->createMCDisassembler(*STI, Ctx)); failIfEmpty(DisAsm, "no disassembler info for target " + TripleName); std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); failIfEmpty(MII, "no instruction info for target " + TripleName); std::unique_ptr<const MCInstrAnalysis> MIA( TheTarget->createMCInstrAnalysis(MII.get())); failIfEmpty(MIA, "no instruction analysis info for target " + TripleName); auto SanCovAddrs = findSanitizerCovFunctions(O); if (SanCovAddrs.empty()) fail("__sanitizer_cov* functions not found"); for (object::SectionRef Section : O.sections()) { if (Section.isVirtual() || !Section.isText()) // llvm-objdump does the same. continue; uint64_t SectionAddr = Section.getAddress(); uint64_t SectSize = Section.getSize(); if (!SectSize) continue; Expected<StringRef> BytesStr = Section.getContents(); failIfError(BytesStr); ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(*BytesStr); for (uint64_t Index = 0, Size = 0; Index < Section.getSize(); Index += Size) { MCInst Inst; if (!DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), SectionAddr + Index, nulls())) { if (Size == 0) Size = 1; continue; } uint64_t Addr = Index + SectionAddr; // Sanitizer coverage uses the address of the next instruction - 1. uint64_t CovPoint = getPreviousInstructionPc(Addr + Size, TheTriple); uint64_t Target; if (MIA->isCall(Inst) && MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target) && SanCovAddrs.find(Target) != SanCovAddrs.end()) Addrs->insert(CovPoint); } } } static void visitObjectFiles(const object::Archive &A, function_ref<void(const object::ObjectFile &)> Fn) { Error Err = Error::success(); for (auto &C : A.children(Err)) { Expected<std::unique_ptr<object::Binary>> ChildOrErr = C.getAsBinary(); failIfError(ChildOrErr); if (auto *O = dyn_cast<object::ObjectFile>(&*ChildOrErr.get())) Fn(*O); else failIfError(object::object_error::invalid_file_type); } failIfError(std::move(Err)); } static void visitObjectFiles(const std::string &FileName, function_ref<void(const object::ObjectFile &)> Fn) { Expected<object::OwningBinary<object::Binary>> BinaryOrErr = object::createBinary(FileName); if (!BinaryOrErr) failIfError(BinaryOrErr); object::Binary &Binary = *BinaryOrErr.get().getBinary(); if (object::Archive *A = dyn_cast<object::Archive>(&Binary)) visitObjectFiles(*A, Fn); else if (object::ObjectFile *O = dyn_cast<object::ObjectFile>(&Binary)) Fn(*O); else failIfError(object::object_error::invalid_file_type); } static std::set<uint64_t> findSanitizerCovFunctions(const std::string &FileName) { std::set<uint64_t> Result; visitObjectFiles(FileName, [&](const object::ObjectFile &O) { auto Addrs = findSanitizerCovFunctions(O); Result.insert(Addrs.begin(), Addrs.end()); }); return Result; } // Locate addresses of all coverage points in a file. Coverage point // is defined as the 'address of instruction following __sanitizer_cov // call - 1'. static std::set<uint64_t> findCoveragePointAddrs(const std::string &FileName) { std::set<uint64_t> Result; visitObjectFiles(FileName, [&](const object::ObjectFile &O) { getObjectCoveragePoints(O, &Result); }); return Result; } static void printCovPoints(const std::string &ObjFile, raw_ostream &OS) { for (uint64_t Addr : findCoveragePointAddrs(ObjFile)) { OS << "0x"; OS.write_hex(Addr); OS << "\n"; } } static ErrorOr<bool> isCoverageFile(const std::string &FileName) { auto ShortFileName = llvm::sys::path::filename(FileName); if (!SancovFileRegex.match(ShortFileName)) return false; ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(FileName); if (!BufOrErr) { errs() << "Warning: " << BufOrErr.getError().message() << "(" << BufOrErr.getError().value() << "), filename: " << llvm::sys::path::filename(FileName) << "\n"; return BufOrErr.getError(); } std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get()); if (Buf->getBufferSize() < 8) { return false; } const FileHeader *Header = reinterpret_cast<const FileHeader *>(Buf->getBufferStart()); return Header->Magic == BinCoverageMagic; } static bool isSymbolizedCoverageFile(const std::string &FileName) { auto ShortFileName = llvm::sys::path::filename(FileName); return SymcovFileRegex.match(ShortFileName); } static std::unique_ptr<SymbolizedCoverage> symbolize(const RawCoverage &Data, const std::string ObjectFile) { auto Coverage = std::make_unique<SymbolizedCoverage>(); ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(ObjectFile); failIfError(BufOrErr); SHA1 Hasher; Hasher.update((*BufOrErr)->getBuffer()); Coverage->BinaryHash = toHex(Hasher.final()); Blacklists B; auto Symbolizer(createSymbolizer()); for (uint64_t Addr : *Data.Addrs) { // TODO: it would be neccessary to set proper section index here. // object::SectionedAddress::UndefSection works for only absolute addresses. auto LineInfo = Symbolizer->symbolizeCode( ObjectFile, {Addr, object::SectionedAddress::UndefSection}); failIfError(LineInfo); if (B.isBlacklisted(*LineInfo)) continue; Coverage->CoveredIds.insert(utohexstr(Addr, true)); } std::set<uint64_t> AllAddrs = findCoveragePointAddrs(ObjectFile); if (!std::includes(AllAddrs.begin(), AllAddrs.end(), Data.Addrs->begin(), Data.Addrs->end())) { fail("Coverage points in binary and .sancov file do not match."); } Coverage->Points = getCoveragePoints(ObjectFile, AllAddrs, *Data.Addrs); return Coverage; } struct FileFn { bool operator<(const FileFn &RHS) const { return std::tie(FileName, FunctionName) < std::tie(RHS.FileName, RHS.FunctionName); } std::string FileName; std::string FunctionName; }; static std::set<FileFn> computeFunctions(const std::vector<CoveragePoint> &Points) { std::set<FileFn> Fns; for (const auto &Point : Points) { for (const auto &Loc : Point.Locs) { Fns.insert(FileFn{Loc.FileName, Loc.FunctionName}); } } return Fns; } static std::set<FileFn> computeNotCoveredFunctions(const SymbolizedCoverage &Coverage) { auto Fns = computeFunctions(Coverage.Points); for (const auto &Point : Coverage.Points) { if (Coverage.CoveredIds.find(Point.Id) == Coverage.CoveredIds.end()) continue; for (const auto &Loc : Point.Locs) { Fns.erase(FileFn{Loc.FileName, Loc.FunctionName}); } } return Fns; } static std::set<FileFn> computeCoveredFunctions(const SymbolizedCoverage &Coverage) { auto AllFns = computeFunctions(Coverage.Points); std::set<FileFn> Result; for (const auto &Point : Coverage.Points) { if (Coverage.CoveredIds.find(Point.Id) == Coverage.CoveredIds.end()) continue; for (const auto &Loc : Point.Locs) { Result.insert(FileFn{Loc.FileName, Loc.FunctionName}); } } return Result; } typedef std::map<FileFn, std::pair<uint32_t, uint32_t>> FunctionLocs; // finds first location in a file for each function. static FunctionLocs resolveFunctions(const SymbolizedCoverage &Coverage, const std::set<FileFn> &Fns) { FunctionLocs Result; for (const auto &Point : Coverage.Points) { for (const auto &Loc : Point.Locs) { FileFn Fn = FileFn{Loc.FileName, Loc.FunctionName}; if (Fns.find(Fn) == Fns.end()) continue; auto P = std::make_pair(Loc.Line, Loc.Column); auto I = Result.find(Fn); if (I == Result.end() || I->second > P) { Result[Fn] = P; } } } return Result; } static void printFunctionLocs(const FunctionLocs &FnLocs, raw_ostream &OS) { for (const auto &P : FnLocs) { OS << stripPathPrefix(P.first.FileName) << ":" << P.second.first << " " << P.first.FunctionName << "\n"; } } CoverageStats computeStats(const SymbolizedCoverage &Coverage) { CoverageStats Stats = {Coverage.Points.size(), Coverage.CoveredIds.size(), computeFunctions(Coverage.Points).size(), computeCoveredFunctions(Coverage).size()}; return Stats; } // Print list of covered functions. // Line format: <file_name>:<line> <function_name> static void printCoveredFunctions(const SymbolizedCoverage &CovData, raw_ostream &OS) { auto CoveredFns = computeCoveredFunctions(CovData); printFunctionLocs(resolveFunctions(CovData, CoveredFns), OS); } // Print list of not covered functions. // Line format: <file_name>:<line> <function_name> static void printNotCoveredFunctions(const SymbolizedCoverage &CovData, raw_ostream &OS) { auto NotCoveredFns = computeNotCoveredFunctions(CovData); printFunctionLocs(resolveFunctions(CovData, NotCoveredFns), OS); } // Read list of files and merges their coverage info. static void readAndPrintRawCoverage(const std::vector<std::string> &FileNames, raw_ostream &OS) { std::vector<std::unique_ptr<RawCoverage>> Covs; for (const auto &FileName : FileNames) { auto Cov = RawCoverage::read(FileName); if (!Cov) continue; OS << *Cov.get(); } } static std::unique_ptr<SymbolizedCoverage> merge(const std::vector<std::unique_ptr<SymbolizedCoverage>> &Coverages) { if (Coverages.empty()) return nullptr; auto Result = std::make_unique<SymbolizedCoverage>(); for (size_t I = 0; I < Coverages.size(); ++I) { const SymbolizedCoverage &Coverage = *Coverages[I]; std::string Prefix; if (Coverages.size() > 1) { // prefix is not needed when there's only one file. Prefix = utostr(I); } for (const auto &Id : Coverage.CoveredIds) { Result->CoveredIds.insert(Prefix + Id); } for (const auto &CovPoint : Coverage.Points) { CoveragePoint NewPoint(CovPoint); NewPoint.Id = Prefix + CovPoint.Id; Result->Points.push_back(NewPoint); } } if (Coverages.size() == 1) { Result->BinaryHash = Coverages[0]->BinaryHash; } return Result; } static std::unique_ptr<SymbolizedCoverage> readSymbolizeAndMergeCmdArguments(std::vector<std::string> FileNames) { std::vector<std::unique_ptr<SymbolizedCoverage>> Coverages; { // Short name => file name. std::map<std::string, std::string> ObjFiles; std::string FirstObjFile; std::set<std::string> CovFiles; // Partition input values into coverage/object files. for (const auto &FileName : FileNames) { if (isSymbolizedCoverageFile(FileName)) { Coverages.push_back(SymbolizedCoverage::read(FileName)); } auto ErrorOrIsCoverage = isCoverageFile(FileName); if (!ErrorOrIsCoverage) continue; if (ErrorOrIsCoverage.get()) { CovFiles.insert(FileName); } else { auto ShortFileName = llvm::sys::path::filename(FileName); if (ObjFiles.find(std::string(ShortFileName)) != ObjFiles.end()) { fail("Duplicate binary file with a short name: " + ShortFileName); } ObjFiles[std::string(ShortFileName)] = FileName; if (FirstObjFile.empty()) FirstObjFile = FileName; } } SmallVector<StringRef, 2> Components; // Object file => list of corresponding coverage file names. std::map<std::string, std::vector<std::string>> CoverageByObjFile; for (const auto &FileName : CovFiles) { auto ShortFileName = llvm::sys::path::filename(FileName); auto Ok = SancovFileRegex.match(ShortFileName, &Components); if (!Ok) { fail("Can't match coverage file name against " "<module_name>.<pid>.sancov pattern: " + FileName); } auto Iter = ObjFiles.find(std::string(Components[1])); if (Iter == ObjFiles.end()) { fail("Object file for coverage not found: " + FileName); } CoverageByObjFile[Iter->second].push_back(FileName); }; for (const auto &Pair : ObjFiles) { auto FileName = Pair.second; if (CoverageByObjFile.find(FileName) == CoverageByObjFile.end()) errs() << "WARNING: No coverage file for " << FileName << "\n"; } // Read raw coverage and symbolize it. for (const auto &Pair : CoverageByObjFile) { if (findSanitizerCovFunctions(Pair.first).empty()) { errs() << "WARNING: Ignoring " << Pair.first << " and its coverage because __sanitizer_cov* functions were not " "found.\n"; continue; } for (const std::string &CoverageFile : Pair.second) { auto DataOrError = RawCoverage::read(CoverageFile); failIfError(DataOrError); Coverages.push_back(symbolize(*DataOrError.get(), Pair.first)); } } } return merge(Coverages); } } // namespace int main(int Argc, char **Argv) { // Print stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(Argv[0]); PrettyStackTraceProgram X(Argc, Argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllDisassemblers(); cl::ParseCommandLineOptions(Argc, Argv, "Sanitizer Coverage Processing Tool (sancov)\n\n" " This tool can extract various coverage-related information from: \n" " coverage-instrumented binary files, raw .sancov files and their " "symbolized .symcov version.\n" " Depending on chosen action the tool expects different input files:\n" " -print-coverage-pcs - coverage-instrumented binary files\n" " -print-coverage - .sancov files\n" " <other actions> - .sancov files & corresponding binary " "files, .symcov files\n" ); // -print doesn't need object files. if (Action == PrintAction) { readAndPrintRawCoverage(ClInputFiles, outs()); return 0; } else if (Action == PrintCovPointsAction) { // -print-coverage-points doesn't need coverage files. for (const std::string &ObjFile : ClInputFiles) { printCovPoints(ObjFile, outs()); } return 0; } auto Coverage = readSymbolizeAndMergeCmdArguments(ClInputFiles); failIf(!Coverage, "No valid coverage files given."); switch (Action) { case CoveredFunctionsAction: { printCoveredFunctions(*Coverage, outs()); return 0; } case NotCoveredFunctionsAction: { printNotCoveredFunctions(*Coverage, outs()); return 0; } case StatsAction: { outs() << computeStats(*Coverage); return 0; } case MergeAction: case SymbolizeAction: { // merge & symbolize are synonims. json::OStream W(outs(), 2); W << *Coverage; return 0; } case HtmlReportAction: errs() << "-html-report option is removed: " "use -symbolize & coverage-report-server.py instead\n"; return 1; case PrintAction: case PrintCovPointsAction: llvm_unreachable("unsupported action"); } }
; this program is from chapter 8 of the book. ; Program to count occurrences of a character in a file. ; Character to be input from the keyboard. ; Result to be displayed on the monitor. ; Program works only if no more than 9 occurrences are found. ; ; ; Initialization ; .ORIG x3000 AND R2,R2,#0 ; R2 is counter, initialize to 0 LD R3,PTR ; R3 is pointer to characters TRAP x23 ; R0 gets character input LDR R1,R3,#0 ; R1 gets the next character ; ; Test character for end of file ; ; TEST ADD R4,R1,#-4 ; Test for EOT BRz OUTPUT ; If done, prepare the output ; ; Test character for match. If a match, increment count. ; NOT R1,R1 ADD R1,R1,#1 ; R1 <-- -R1 ADD R1,R1,R0 ; R1 <-- R0-R1. If R1=0, a match! BRnp GETCHAR ; If no match, do not increment ADD R2,R2,#1 ; ; Get next character from the file ; GETCHAR ADD R3,R3,#1 ; Increment the pointer LDR R1,R3,#0 ; R1 gets the next character to test BRnzp TEST ; ; Output the count. ; OUTPUT LD R0,ASCII ; Load the ASCII template ADD R0,R0,R2 ; Convert binary to ASCII TRAP x21 ; ASCII code in R0 is displayed TRAP x25 ; Halt machine ; ; Storage for pointer and ASCII template ; ASCII .FILL x0030 PTR .FILL x4000 .END
CHAR_CLRSCR equ 147 ; ----------------------------------------------------------------- ; Implements a jump table to select various interrupt routines. ; Input: ; BP - offset to the function table ; AH - function number ; ----------------------------------------------------------------- INT_Dispatch: push bx mov bl, ah xor bh, bh shl bx, 1 add bp, bx pop bx call [cs:bp] ret INT_Unimplemented: ret ; ----------------------------------------------------------------- ; INT 10 - screen functions moved to screen.asm ; ----------------------------------------------------------------- ; ----------------------------------------------------------------- ; INT 11 - equipment list. ; ----------------------------------------------------------------- INT_11: INT_Debug 11h ; Detect 8087 processor call INT_11_CPU and ax, 0001h shl ax, 1 ; 2 disk drives, MDA card, 64K+ memory, 1 serial port add ax, 037Dh iret ; ----------------------------------------------------------------- ; Equipment flags. ; ----------------------------------------------------------------- EQUIPMENT_8087 equ 1 EQUIPMENT_V20 equ 2 INT_11_CPU: push cx push bx ; Test if 8087 present fninit mov cx, 3 INT_11_CPU_8087: loop INT_11_CPU_8087 mov bx, sp sub bx, 2 mov [ss:bx], ax fnstcw [ss:bx] cmp [ss:bx], word 03FFh jne INT_11_CPU_No8087 mov cl, EQUIPMENT_8087 INT_11_CPU_No8087: pop bx pop cx ret db 60h ; PUSHA stc jnc INT_11_CPU_NoV20 db 61h ; POPA or cl, EQUIPMENT_V20 INT_11_CPU_NoV20: mov al, cl pop bx pop cx ret ; ----------------------------------------------------------------- ; INT 12 - memory size. ; ----------------------------------------------------------------- INT_12: INT_Debug 12h mov ax, (MemTop-40h)/64 iret ; ----------------------------------------------------------------- ; INT 13 - disk functions. ; ----------------------------------------------------------------- INT_13: INT_Debug 13h cmp ah, 1Bh ja INT_13_Ret push bp mov bp, INT_13_Functions call INT_Dispatch pop bp retf 2 INT_13_Ret: iret INT_13_Functions: dw INT_13_OK dw INT_13_01 dw INT_13_02 dw INT_13_03 dw INT_13_OK dw INT_13_Error dw INT_13_Error dw INT_13_Error dw INT_13_08 dw INT_13_Error dw INT_13_Error dw INT_13_Error dw INT_13_OK dw INT_13_OK dw INT_13_Error dw INT_13_Error dw INT_13_OK dw INT_13_Error dw INT_13_Error dw INT_13_Error dw INT_13_Error dw INT_13_15 dw INT_13_16 dw INT_13_Error dw INT_13_Error dw INT_13_Error dw INT_13_Error INT_13_HD: cmp dl, 080h jne INT_13_HD_1 jmp SD_Handle INT_13_HD_1: ret ; ----------------------------------------------------------------- ; INT 13 function 00 - reset drive. ; ----------------------------------------------------------------- INT_13_OK: clc ret INT_13_Error: stc mov al, 02h ret ; ----------------------------------------------------------------- ; INT 13 function 01 - get status. ; ----------------------------------------------------------------- INT_13_01: clc xor al, al ret ; ----------------------------------------------------------------- ; INT 13 function 02 - disk read. ; INT 13 function 03 - disk write. ; ----------------------------------------------------------------- INT_13_02: test dl, 80h jnz INT_13_HD INT_13_02_Floppy: mov bp, 0 jmp INT_13_Common INT_13_03: test dl, 80h jnz INT_13_HD mov bp, 1 INT_13_Common: push es push cx push ax push ax call INT_13_Logical pop cx xor ch, ch INT_13_02_Loop: call INT_13_Disk jc INT_13_02_Error inc ax inc ch cmp ch, cl jne INT_13_02_Loop INT_13_02_Break: mov al, ch xor ah, ah INT_13_02_Ret: pop cx pop cx pop es ret INT_13_02_Error: mov al, ch jmp INT_13_02_Ret ; ----------------------------------------------------------------- ; Calculate logical sector number from PC geometry. ; Input: ; CL - physical sector number ; DH - physical head number ; CH - physical track number ; Output: ; AX - logical sector number ; ----------------------------------------------------------------- INT_13_Logical: push bx push ds mov ax, Data_Segment mov ds, ax mov al, ch xor ah, ah mov bl, 2 mul bl add al, dh mov bl, 9 mul bl mov bl, cl dec bl xor bh, bh add ax, bx pop ds pop bx ret ; ----------------------------------------------------------------- ; Read or write PC sector ; Input: ; BP - 0 for disk read, 1 for disk write ; AX - 256-byte sector number ; DL - drive number ; ES:BX - buffer address ; ----------------------------------------------------------------- INT_13_Disk: push cx push ax ; Convert 512- to 256-byte sectors push ds mov cx, Data_Segment mov ds, cx mov cl, 2 xor ch, ch push dx mul cx pop dx pop ds ; Check if read across 64 kB boundary push ax push bx mov ax, es shl ax, 1 shl ax, 1 shl ax, 1 shl ax, 1 add ax, bx test ax, ax jz INT_13_Disk_Zero xchg ax, bx mov ax, 1 mul cl xchg al, ah add ax, bx jc INT_13_Disk_DMA_Error pop bx pop ax ; Read physical sectors INT_13_Disk_Loop: push ax call IPC_SectorCalc call IPC_SectorAccess cmp ax, 3030h jz INT_13_Disk_NoError pop ax pop ax pop cx stc mov ah, 2 ret INT_13_Disk_NoError: ; Check if we were reading on the 0000 boundary ; If yes, move the sector 2 bytes below and restore overwritten word test ch, 01h jz INT_13_NotZero push ds push si push di mov di, es mov ds, di sub bx, 2 mov si, bx mov di, bx push cx mov cx, 128 lodsw rep movsw pop cx xor ch, ch stosw pop di pop si pop ds INT_13_NotZero: mov ax, es add ax, 16 mov es, ax pop ax inc ax loop INT_13_Disk_Loop pop ax pop cx clc ret ; Fake "read across 64 boundary" error INT_13_Disk_DMA_Error: pop bx pop ax pop ax pop cx stc mov ah, 9 ret ; Read on 0000-aligned address: move the pointer +2 bytes INT_13_Disk_Zero: pop bx ; Remember the word that will be overwritten mov ax, [es:bx+256] cmp bp, 1 jne INT_13_Disk_NotWrite ; If writing, move the sector 2 bytes up push ds push si push di mov si, es mov ds, si mov si, bx add si, 254 mov di, bx add di, 256 std push cx mov cx, 128 rep movsw pop cx cld pop di pop si pop ds INT_13_Disk_NotWrite: mov [es:bx], ax add bx, 2 pop ax mov ch, 01h jmp INT_13_Disk_Loop ; ----------------------------------------------------------------- ; INT 13 function 08 - get drive parameters. ; ----------------------------------------------------------------- INT_13_08: test dl, 80h jz INT_13_08_Floppy jmp INT_13_HD INT_13_08_Floppy: clc xor ah, ah mov bl, 03h mov cx, 5009h mov dx, 0102h mov di, INT_1E push cs pop es ret ; ----------------------------------------------------------------- ; INT 13 function 15 - get disk change type. ; ----------------------------------------------------------------- INT_13_15: test dl, 80h jz INT_13_15_Floppy jmp INT_13_HD INT_13_15_Floppy: clc mov ah, 01h ret ; ----------------------------------------------------------------- ; INT 13 function 16 - get disk change flag. ; ----------------------------------------------------------------- INT_13_16: clc mov ah, 01h ret ; ----------------------------------------------------------------- ; INT 14 - serial functions. ; ----------------------------------------------------------------- INT_14: INT_Debug 14h cmp ah, 03h ja INT_14_Ret push bp mov bp, INT_14_Functions call INT_Dispatch pop bp INT_14_Ret: iret INT_14_Functions: dw INT_14_00 dw INT_14_01 dw INT_14_02 dw INT_14_03 ; ----------------------------------------------------------------- ; INT 14 function 00 - initialize serial port (unimplemented). ; ----------------------------------------------------------------- INT_14_00: ret ; ----------------------------------------------------------------- ; INT 14 function 01 - send character. ; ----------------------------------------------------------------- INT_14_01: test dx, dx jnz INT_14_NoPort call IPC_SerialOut xor ah, ah ret INT_14_NoPort: ret ; ----------------------------------------------------------------- ; INT 14 function 02 - receive character. ; ----------------------------------------------------------------- INT_14_02: test dx, dx jnz INT_14_NoPort call IPC_SerialIn xor ah, ah ret ; ----------------------------------------------------------------- ; INT 14 function 03 - get serial port status. ; ----------------------------------------------------------------- INT_14_03: test dx, dx jnz INT_14_NoPort mov ax, 6110h ret ; ----------------------------------------------------------------- ; INT 15 - BIOS functions. ; ----------------------------------------------------------------- INT_15: INT_Debug 15h stc retf 2 ; ----------------------------------------------------------------- ; INT 16 - keyboard functions. ; ----------------------------------------------------------------- INT_16: INT_Debug 16h and ah, 0EFh cmp ah, 03h ja INT_16_Ret push bp mov bp, INT_16_Functions call INT_Dispatch pop bp retf 2 ; To retain the ZF flag! INT_16_Ret: iret INT_16_Functions: dw INT_16_00 dw INT_16_01 dw INT_16_02 dw INT_Unimplemented ; ----------------------------------------------------------------- ; INT 16 function 00 - read from keyboard buffer. ; ----------------------------------------------------------------- INT_16_00: call Screen_Interrupt call IPC_KbdPeek jz INT_16_00 push ax call INT_16_BIOSFlags pop ax call IPC_KbdClear jmp IPC_KbdConvert ; ----------------------------------------------------------------- ; INT 16 function 01 - peek into keyboard buffer. ; ----------------------------------------------------------------- INT_16_01: call Screen_Interrupt call IPC_KbdPeek jz INT_16_NoKey push ax call INT_16_BIOSFlags pop ax jmp IPC_KbdConvert INT_16_NoKey: xor ax, ax ret ; ----------------------------------------------------------------- ; INT 16 function 02 - get shift key state. ; ----------------------------------------------------------------- INT_16_02: call IPC_KbdPeek ; Store shift key state in BIOS data area for Turbo Pascal 7 INT_16_BIOSFlags: xor al, al test ah, 10h jnz INT_16_BIOSFlags_NoShift or al, 01h INT_16_BIOSFlags_NoShift: test ah, 20h jnz INT_16_BIOSFlags_NoCtrl or al, 04h INT_16_BIOSFlags_NoCtrl: test ah, 08h jnz INT_16_BIOSFlags_NoAlt or al, 08h INT_16_BIOSFlags_NoAlt: push bx push ds xor bx, bx mov ds, bx mov [0417h], al pop ds pop bx ret ; ----------------------------------------------------------------- ; INT 17 - printer functions. ; ----------------------------------------------------------------- INT_17: INT_Debug 17h cmp ah, 02h ja INT_17_Ret push bp mov bp, INT_17_Functions call INT_Dispatch pop bp INT_17_Ret: iret INT_17_Functions: dw INT_17_00 dw INT_17_01 dw INT_17_02 ; ----------------------------------------------------------------- ; INT 17 function 00 - output byte to printer. ; ----------------------------------------------------------------- INT_17_00: call IPC_PrinterOut ret ; ----------------------------------------------------------------- ; INT 17 function 01 - initialize printer (unimplemented). ; ----------------------------------------------------------------- INT_17_01: ret ; ----------------------------------------------------------------- ; INT 17 function 02 - get printer status. ; ----------------------------------------------------------------- INT_17_02: mov ah, 80h ret ; ----------------------------------------------------------------- ; INT 18 - ROM BASIC. ; ----------------------------------------------------------------- INT_18: INT_Debug 18h jmp INT_19_Again ; ----------------------------------------------------------------- ; INT 19 - Reboot. ; ----------------------------------------------------------------- INT_19: INT_Debug 19h INT_19_Again: push cs pop ds call Output_Line mov si, INT_19_Banner1 call Output_String INT_19_Loop: call INT_16_00 cmp ah, 3Ch ; F2 jz INT_19_Floppy cmp ah, 3Bh ; F1 jz INT_19_HD cmp ah, 44h ; F10 jz Config_Modify cmp ax, 02E03h ; Run/Stop jz Config_Reset jmp INT_19_Loop ; Try loading boot sector from hard disk INT_19_HD: call Output_Line mov dx, 0080h mov ax, 0201h xor cx, cx mov es, cx inc cx mov bx, 7C00h call INT_13_02 jc INT_19_Error cmp [es:7DFEh], word 0AA55h jne INT_19_NoSystem mov dl, 80h jmp INT_19_Found INT_19_Floppy: call Output_Line ; Load two first 256-byte sectors from the floppy disk. xor bx, bx mov es, bx mov bp, bx mov bx, 7C00h xor dl, dl mov ax, 0001h call IPC_SectorAccess mov bx, 7D00h mov ax, 0101h call IPC_SectorAccess cmp [es:7DFEh], word 0AA55h jne INT_19_NoSystem xor dl, dl INT_19_Found: push dx call IPC_Init ; Jump to boot sector code. call INT_19_Segments mov si, INT_19_Banner2 call Output_String mov [es:Data_Boot], byte 80h pop dx jmp 0000:7C00h INT_19_NoSystem: call INT_19_Segments mov si, INT_19_Banner3 call Output_String jmp INT_19_Again INT_19_Segments: mov ax, Data_Segment mov es, ax push cs pop ds ret INT_19_Error: call INT_19_Segments mov si, INT_19_Banner4 call Output_String jmp INT_19_Again INT_19_Banner1: db "Select an option:", 10, 13 db " F1 - Boot from SD card", 10, 13 db " F2 - Boot from floppy disk", 10, 13 db " F10 - Modify configuration", 10, 13 db " Run/Stop - Reset configuration", 10, 13 db 0 INT_19_Banner4: db "SD card not found, please try again.", 10, 13, 0 INT_19_Banner2: db "The system is coming up, please wait.", 10, 13, 0 INT_19_Banner3: db "Insert a system disk and press any key.", 10, 13, 0 ; ----------------------------------------------------------------- ; INT 1A - Timer functions. ; ----------------------------------------------------------------- INT_1A: INT_Debug 1Ah test ah, ah je INT_1A_00 cmp ah, 01 je INT_1A_01 cmp ah, 02 je INT_1A_02 cmp ah, 03 je INT_1A_03 cmp ah, 04 je INT_1A_04 cmp ah, 05 je INT_1A_05 stc xor dx, dx xor cx, cx retf 2 ; ----------------------------------------------------------------- ; INT 1A function 00 - get system time. ; ----------------------------------------------------------------- INT_1A_00: push ds xor cx, cx mov ds, cx mov dx, [046Ch] mov cx, [046Eh] xor al, al pop ds clc retf 2 ; push ax ; push bx ; call INT_1A_02_Do ; mov al, dh ; call ConvertFromBCD ; mov ah, al ; AH = Seconds ; push ax ; mov al, cl ; call ConvertFromBCD ; mov dl, al ; DL = Minutes ; mov al, ch ; call ConvertFromBCD ; mov dh, al ; DH = Hours ; pop ax ; xor al, al ; AL = Microseconds ; Calculate number of ticks in whole minutes ; mov bx, ax ; mov al, dh ; mov cl, 60 ; mul cl ; xor dh, dh ; add ax, dx ; mov cx, 1092 ; Ticks per minute ; mul cx ; push dx ; push ax ; Calculate number of ticks in seconds ; mov al, bh ; mov cl, 10 ; mul cl ; xor bh, bh ; add ax, bx ; mov cx, 182 ; mul cx ; mov cx, 100 ; div cx ; Add them together ; pop cx ; add cx, ax ; pop dx ; xor ax, ax ; adc dx, ax ; pop bx ; pop ax ; xor al, al ; xchg cx, dx ; iret ; ----------------------------------------------------------------- ; INT 1A function 01 - set system time. ; ----------------------------------------------------------------- INT_1A_01: push ax push ds xor ax, ax mov ds, ax mov [046Ch], dx mov [046Eh], cx pop ds pop ax clc retf 2 ; push ax ; push bx ; push cx ; push dx ; mov ax, dx ; mov dx, cx ; Calculate hour and minute ; mov cx, 1092 ; Ticks per minute ; div cx ; mov bx, dx ; mov cl, 60 ; div cl ; xchg al, ah ; Calculate number of seconds ; xchg ax, bx ; xor dx, dx ; mov cx, 50 ; mul cx ; mov cx, 91 ; div cx ; mov cl, 10 ; div cl ; xchg al, ah ; mov dx, bx ; push ax ; mov al, dh ; call ConvertToBCD ; mov ch, al ; mov al, dl ; call ConvertToBCD ; mov cl, al ; pop ax ; mov al, ah ; call ConvertToBCD ; mov dh, al ; call INT_1A_03_Do ; pop dx ; pop cx ; pop bx ; pop ax ; iret ; ----------------------------------------------------------------- ; INT 1A function 02 - get RTC time. ; ----------------------------------------------------------------- INT_1A_02: call INT_1A_02_Do retf 2 INT_1A_02_Do: push ax call I2C_Start ; RTC adress + write flag mov al, 0D0h call I2C_Send jnc INT_1A_02_Do2 call I2C_Stop pop ax stc ret INT_1A_02_Do2: ; Read start address mov al, 00h call I2C_Send call I2C_Start ; RTC adress + read flag mov al, 0D1h call I2C_Send ; Read address 00 (seconds) clc call I2C_Receive and al, 7Fh mov dh, al ; Read address 01 (minutes) clc call I2C_Receive mov cl, al ; Read address 02 (seconds) stc call I2C_Receive mov ch, al xor dl, dl call I2C_Stop pop ax clc ret ; ----------------------------------------------------------------- ; INT 1A function 03 - set RTC time. ; ----------------------------------------------------------------- INT_1A_03: call INT_1A_03_Do retf 2 INT_1A_03_Do: push ax call I2C_Start ; RTC adress + write flag mov al, 0D0h call I2C_Send jnc INT_1A_03_Do2 call I2C_Stop pop ax stc ret INT_1A_03_Do2: ; Write start address mov al, 00h call I2C_Send ; Write address 00 (seconds) mov al, dh call I2C_Send ; Write address 01 (minutes) mov al, cl call I2C_Send ; Write address 02 (seconds) mov al, ch call I2C_Send call I2C_Stop pop ax clc ret INT_1A_NoRTC: call I2C_Stop pop ax stc iret ; ----------------------------------------------------------------- ; INT 1A function 04 - get RTC date. ; ----------------------------------------------------------------- INT_1A_04: push ax call I2C_Start ; RTC adress + write flag mov al, 0D0h call I2C_Send jc INT_1A_NoRTC ; Read start address mov al, 04h call I2C_Send call I2C_Start ; RTC adress + read flag mov al, 0D1h call I2C_Send ; Read address 04 (day) clc call I2C_Receive mov dl, al ; Read address 05 (month) clc call I2C_Receive mov dh, al ; Read address 06 (year) stc call I2C_Receive mov cl, al mov ch, 020h call I2C_Stop pop ax clc retf 2 ; ----------------------------------------------------------------- ; INT 1A function 05 - set RTC date. ; ----------------------------------------------------------------- INT_1A_05: push ax call I2C_Start ; RTC adress + write flag mov al, 0D0h call I2C_Send jc INT_1A_NoRTC ; Write start address mov al, 04h call I2C_Send ; Write address 04 (day) mov al, dl call I2C_Send ; Write address 05 (month) mov al, dh call I2C_Send ; Write address 06 (year) mov al, cl call I2C_Send call I2C_Stop pop ax clc retf 2 ; ----------------------------------------------------------------- ; Convert BCD to decimal ; ----------------------------------------------------------------- ConvertFromBCD: mov bh, al and bh, 0Fh shr al, 1 shr al, 1 shr al, 1 shr al, 1 mov bl, 10 mul bl add al, bh ret ; ----------------------------------------------------------------- ; Convert decimal to BCD ; ----------------------------------------------------------------- ConvertToBCD: aam shl ah, 1 shl ah, 1 shl ah, 1 shl ah, 1 or al, ah ret ; ----------------------------------------------------------------- ; INT 1B - Ctrl+Break. ; ----------------------------------------------------------------- INT_1B: INT_Debug 1Bh iret ; ----------------------------------------------------------------- ; INT 1C - System tick. ; ----------------------------------------------------------------- INT_1C: ; INT_Debug 1Ch iret ; ----------------------------------------------------------------- ; INT 1E - disk parameter table. ; ----------------------------------------------------------------- INT_1E: db 0DFh db 02h db 25h db 02h db 09h db 2Ah db 0FFh db 50h db 0F6h db 0Fh db 02h db 00h
/* * Copyright 2018- The Pixie Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ #include "src/stirling/source_connectors/socket_tracer/protocols/kafka/stitcher.h" #include <deque> #include <string> #include <unordered_map> #include <utility> #include "src/common/base/base.h" #include "src/stirling/source_connectors/socket_tracer/protocols/kafka/common/types.h" #include "src/stirling/source_connectors/socket_tracer/protocols/kafka/decoder/packet_decoder.h" namespace px { namespace stirling { namespace protocols { namespace kafka { Status ProcessProduceReq(PacketDecoder* decoder, Request* req) { PL_ASSIGN_OR_RETURN(ProduceReq r, decoder->ExtractProduceReq()); req->msg = ToString(r); return Status::OK(); } Status ProcessProduceResp(PacketDecoder* decoder, Response* resp) { PL_ASSIGN_OR_RETURN(ProduceResp r, decoder->ExtractProduceResp()); resp->msg = ToString(r); return Status::OK(); } Status ProcessFetchReq(PacketDecoder* decoder, Request* req) { PL_ASSIGN_OR_RETURN(FetchReq r, decoder->ExtractFetchReq()); req->msg = ToString(r); return Status::OK(); } Status ProcessFetchResp(PacketDecoder* decoder, Response* resp) { PL_ASSIGN_OR_RETURN(FetchResp r, decoder->ExtractFetchResp()); resp->msg = ToString(r); return Status::OK(); } Status ProcessReq(Packet* req_packet, Request* req) { req->timestamp_ns = req_packet->timestamp_ns; PacketDecoder decoder(*req_packet); // Extracts api_key, api_version, and correlation_id. PL_RETURN_IF_ERROR(decoder.ExtractReqHeader(req)); // TODO(chengruizhe): Add support for more api keys. switch (req->api_key) { case APIKey::kProduce: return ProcessProduceReq(&decoder, req); case APIKey::kFetch: return ProcessFetchReq(&decoder, req); default: VLOG(1) << absl::Substitute("Unparsed cmd $0", magic_enum::enum_name(req->api_key)); } return Status::OK(); } Status ProcessResp(Packet* resp_packet, Response* resp, APIKey api_key, int16_t api_version) { resp->timestamp_ns = resp_packet->timestamp_ns; PacketDecoder decoder(*resp_packet); decoder.SetAPIInfo(api_key, api_version); PL_RETURN_IF_ERROR(decoder.ExtractRespHeader(resp)); switch (api_key) { case APIKey::kProduce: return ProcessProduceResp(&decoder, resp); case APIKey::kFetch: return ProcessFetchResp(&decoder, resp); // TODO(chengruizhe): Add support for more api keys. default: VLOG(1) << absl::Substitute("Unparsed cmd $0", magic_enum::enum_name(api_key)); } return Status::OK(); } StatusOr<Record> ProcessReqRespPair(Packet* req_packet, Packet* resp_packet) { ECHECK_LT(req_packet->timestamp_ns, resp_packet->timestamp_ns); Record r; PL_RETURN_IF_ERROR(ProcessReq(req_packet, &r.req)); PL_RETURN_IF_ERROR(ProcessResp(resp_packet, &r.resp, r.req.api_key, r.req.api_version)); return r; } // Kafka StitchFrames uses a hashmap to store a mapping of correlation_ids to resp_packets. // For each req_packet, it looks for the corresponding resp_packet in the map. // All the resp_packets, whether matched with a request or not, are popped off at the end of // the function, where req_packets not matched remain in the deque. // Note that this is different from the two for loop implementation used in other stitchers. RecordsWithErrorCount<Record> StitchFrames(std::deque<Packet>* req_packets, std::deque<Packet>* resp_packets) { std::vector<Record> entries; int error_count = 0; // Maps correlation_id to resp packet. std::unordered_map<int32_t, Packet*> correlation_id_map; for (auto& resp_packet : *resp_packets) { correlation_id_map[resp_packet.correlation_id] = &resp_packet; } for (auto& req_packet : *req_packets) { auto it = correlation_id_map.find(req_packet.correlation_id); if (it != correlation_id_map.end()) { StatusOr<Record> record_status = ProcessReqRespPair(&req_packet, it->second); if (record_status.ok()) { entries.push_back(record_status.ConsumeValueOrDie()); } else { VLOG(1) << record_status.ToString(); ++error_count; } // Mark the request as consumed, and clean-up when they reach the head of the queue. req_packet.consumed = true; // Remove resp_packet from map once it's been matched. correlation_id_map.erase(req_packet.correlation_id); } } // Resp packets left in the map don't have a matched request. for (const auto& [correlation_id, resp_packet] : correlation_id_map) { VLOG(1) << absl::Substitute("Did not find a request matching the response. Correlation ID = $0", correlation_id); ++error_count; } // Clean-up consumed req_packets at the head. for (const auto& req_packet : *req_packets) { if (!req_packet.consumed) { break; } req_packets->pop_front(); } resp_packets->clear(); // TODO(chengruizhe): Remove req_packets that are too old. return {entries, error_count}; } } // namespace kafka } // namespace protocols } // namespace stirling } // namespace px
; Fibonacci Sequence Display ; ; Display the Fibonacci sequence for the range that is caculatable with 8-bit math OUTPUT = $7800 ; The display register is found at address $7800 ; ; Code ; .org 0 ; code starts at address 0 start: mov [OUTPUT],1 ; init display to 1 mov i,1 ; init I to 1, represents second fibonacci number mov j,1 ; init J to 1, represents first fibonacci number mov a,i ; init A with current fibonacci in register I loop: add j ; add J to A to yield next fibonacci number jc start ; if there was a carry, then we can't calculate any more fibonacci. restart. mov [OUTPUT],a ; display next fibonnaci number mov j,i ; move last fibonacci to previous to last fibonacci mov i,a ; move current fibonacci to last fibonacci jmp loop ; loop
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %r14 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x14786, %rsi lea addresses_WT_ht+0x148d4, %rdi nop nop nop dec %r13 mov $11, %rcx rep movsq add $64364, %r10 lea addresses_WT_ht+0x3d86, %r10 dec %r13 mov $0x6162636465666768, %rcx movq %rcx, %xmm7 movups %xmm7, (%r10) nop nop nop nop nop sub %rdi, %rdi lea addresses_normal_ht+0xa786, %rdx inc %rbp movw $0x6162, (%rdx) nop nop nop nop and $62523, %rbp lea addresses_normal_ht+0x188f9, %r13 nop dec %rbp vmovups (%r13), %ymm0 vextracti128 $1, %ymm0, %xmm0 vpextrq $0, %xmm0, %rcx nop nop nop nop nop add $33141, %rdi lea addresses_D_ht+0x18f86, %r10 nop nop nop add %rdx, %rdx movb $0x61, (%r10) nop dec %r13 lea addresses_UC_ht+0xad86, %rcx inc %rdi and $0xffffffffffffffc0, %rcx movaps (%rcx), %xmm7 vpextrq $0, %xmm7, %rdx nop nop nop nop nop sub %rbp, %rbp lea addresses_A_ht+0x16026, %rbp clflush (%rbp) nop nop inc %rdi movw $0x6162, (%rbp) nop inc %rbp lea addresses_D_ht+0x15286, %rsi lea addresses_normal_ht+0x6526, %rdi nop xor %r14, %r14 mov $69, %rcx rep movsb nop nop sub %rcx, %rcx lea addresses_normal_ht+0xe186, %r14 nop nop nop nop add $61763, %rbp movb (%r14), %dl nop nop nop nop sub %rbp, %rbp lea addresses_D_ht+0x15186, %rsi lea addresses_normal_ht+0x1a33b, %rdi and %rbp, %rbp mov $62, %rcx rep movsw nop nop nop nop nop cmp %r14, %r14 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r14 pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r13 push %r14 push %r15 push %r8 push %r9 push %rsi // Faulty Load lea addresses_D+0x3d86, %r14 and %r15, %r15 mov (%r14), %r8d lea oracles, %rsi and $0xff, %r8 shlq $12, %r8 mov (%rsi,%r8,1), %r8 pop %rsi pop %r9 pop %r8 pop %r15 pop %r14 pop %r13 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': True, 'congruent': 7, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 16}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 2}} {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1}} {'src': {'NT': True, 'same': True, 'congruent': 11, 'type': 'addresses_UC_ht', 'AVXalign': True, 'size': 16}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': True, 'congruent': 5, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 2}} {'src': {'same': False, 'congruent': 8, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_normal_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 10, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_normal_ht'}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
object_const_def ; object_event constants const VIOLETKYLESHOUSE_POKEFAN_M const VIOLETKYLESHOUSE_KYLE VioletKylesHouse_MapScripts: db 0 ; scene scripts db 0 ; callbacks VioletKylesHousePokefanMScript: jumptextfaceplayer VioletKylesHousePokefanMText Kyle: faceplayer opentext trade NPC_TRADE_KYLE waitbutton closetext end VioletKylesHousePokefanMText: text "A #MON you get" line "in a trade grows" cont "quickly." para "But if you don't" line "have the right GYM" para "BADGE, they may" line "disobey you." done VioletKylesHouse_MapEvents: db 0, 0 ; filler db 2 ; warp events warp_event 3, 7, VIOLET_CITY, 6 warp_event 4, 7, VIOLET_CITY, 6 db 0 ; coord events db 0 ; bg events db 2 ; object events object_event 2, 3, SPRITE_POKEFAN_M, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, VioletKylesHousePokefanMScript, -1 object_event 6, 5, SPRITE_YOUNGSTER, SPRITEMOVEDATA_WALK_UP_DOWN, 0, 2, -1, -1, PAL_NPC_RED, OBJECTTYPE_SCRIPT, 0, Kyle, -1
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2021, ITU/ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ITU/ISO/IEC nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ /** \file SEIFilmGrainSynthesizer.cpp \brief SMPTE RDD5 based film grain synthesis functionality from SEI messages */ #include "SEIFilmGrainSynthesizer.h" #include <stdio.h> #include <cmath> /* static look up table definitions */ static const int8_t gaussianLUT[2048] = { -11, 12, 103, -11, 42, -35, 12, 59, 77, 98, -87, 3, 65, -78, 45, 56, -51, 21, 13, -11, -20, -19, 33, -127, 17, -6, -105, 18, 19, 71, 48, -10, -38, 42, -2, 75, -67, 52, -90, 33, -47, 21, -3, -56, 49, 1, -57, -42, -1, 120, -127, -108, -49, 9, 14, 127, 122, 109, 52, 127, 2, 7, 114, 19, 30, 12, 77, 112, 82, -61, -127, 111, -52, -29, 2, -49, -24, 58, -29, -73, 12, 112, 67, 79, -3, -114, -87, -6, -5, 40, 58, -81, 49, -27, -31, -34, -105, 50, 16, -24, -35, -14, -15, -127, -55, -22, -55, -127, -112, 5, -26, -72, 127, 127, -2, 41, 87, -65, -16, 55, 19, 91, -81, -65, -64, 35, -7, -54, 99, -7, 88, 125, -26, 91, 0, 63, 60, -14, -23, 113, -33, 116, 14, 26, 51, -16, 107, -8, 53, 38, -34, 17, -7, 4, -91, 6, 63, 63, -15, 39, -36, 19, 55, 17, -51, 40, 33, -37, 126, -39, -118, 17, -30, 0, 19, 98, 60, 101, -12, -73, -17, -52, 98, 3, 3, 60, 33, -3, -2, 10, -42, -106, -38, 14, 127, 16, -127, -31, -86, -39, -56, 46, -41, 75, 23, -19, -22, -70, 74, -54, -2, 32, -45, 17, -92, 59, -64, -67, 56, -102, -29, -87, -34, -92, 68, 5, -74, -61, 93, -43, 14, -26, -38, -126, -17, 16, -127, 64, 34, 31, 93, 17, -51, -59, 71, 77, 81, 127, 127, 61, 33, -106, -93, 0, 0, 75, -69, 71, 127, -19, -111, 30, 23, 15, 2, 39, 92, 5, 42, 2, -6, 38, 15, 114, -30, -37, 50, 44, 106, 27, 119, 7, -80, 25, -68, -21, 92, -11, -1, 18, 41, -50, 79, -127, -43, 127, 18, 11, -21, 32, -52, 27, -88, -90, -39, -19, -10, 24, -118, 72, -24, -44, 2, 12, 86, -107, 39, -33, -127, 47, 51, -24, -22, 46, 0, 15, -35, -69, -2, -74, 24, -6, 0, 29, -3, 45, 32, -32, 117, -45, 79, -24, -17, -109, -10, -70, 88, -48, 24, -91, 120, -37, 50, -127, 58, 32, -82, -10, -17, -7, 46, -127, -15, 89, 127, 17, 98, -39, -33, 37, 42, -40, -32, -21, 105, -19, 19, 19, -59, -9, 30, 0, -127, 34, 127, -84, 75, 24, -40, -49, -127, -107, -14, 45, -75, 1, 30, -20, 41, -68, -40, 12, 127, -3, 5, 20, -73, -59, -127, -3, -3, -53, -6, -119, 93, 120, -80, -50, 0, 20, -46, 67, 78, -12, -22, -127, 36, -41, 56, 119, -5, -116, -22, 68, -14, -90, 24, -82, -44, -127, 107, -25, -37, 40, -7, -7, -82, 5, -87, 44, -34, 9, -127, 39, 70, 49, -63, 74, -49, 109, -27, -89, -47, -39, 44, 49, -4, 60, -42, 80, 9, -127, -9, -56, -49, 125, -66, 47, 36, 117, 15, -11, -96, 109, 94, -17, -56, 70, 8, -14, -5, 50, 37, -45, 120, -30, -76, 40, -46, 6, 3, 69, 17, -78, 1, -79, 6, 127, 43, 26, 127, -127, 28, -55, -26, 55, 112, 48, 107, -1, -77, -1, 53, -9, -22, -43, 123, 108, 127, 102, 68, 46, 5, 1, 123, -13, -55, -34, -49, 89, 65, -105, -5, 94, -53, 62, 45, 30, 46, 18, -35, 15, 41, 47, -98, -24, 94, -75, 127, -114, 127, -68, 1, -17, 51, -95, 47, 12, 34, -45, -75, 89, -107, -9, -58, -29, -109, -24, 127, -61, -13, 77, -45, 17, 19, 83, -24, 9, 127, -66, 54, 4, 26, 13, 111, 43, -113, -22, 10, -24, 83, 67, -14, 75, -123, 59, 127, -12, 99, -19, 64, -38, 54, 9, 7, 61, -56, 3, -57, 113, -104, -59, 3, -9, -47, 74, 85, -55, -34, 12, 118, 28, 93, -72, 13, -99, -72, -20, 30, 72, -94, 19, -54, 64, -12, -63, -25, 65, 72, -10, 127, 0, -127, 103, -20, -73, -112, -103, -6, 28, -42, -21, -59, -29, -26, 19, -4, -51, 94, -58, -95, -37, 35, 20, -69, 127, -19, -127, -22, -120, -53, 37, 74, -127, -1, -12, -119, -53, -28, 38, 69, 17, 16, -114, 89, 62, 24, 37, -23, 49, -101, -32, -9, -95, -53, 5, 93, -23, -49, -8, 51, 3, -75, -90, -10, -39, 127, -86, -22, 20, 20, 113, 75, 52, -31, 92, -63, 7, -12, 46, 36, 101, -43, -17, -53, -7, -38, -76, -31, -21, 62, 31, 62, 20, -127, 31, 64, 36, 102, -85, -10, 77, 80, 58, -79, -8, 35, 8, 80, -24, -9, 3, -17, 72, 127, 83, -87, 55, 18, -119, -123, 36, 10, 127, 56, -55, 113, 13, 26, 32, -13, -48, 22, -13, 5, 58, 27, 24, 26, -11, -36, 37, -92, 78, 81, 9, 51, 14, 67, -13, 0, 32, 45, -76, 32, -39, -22, -49, -127, -27, 31, -9, 36, 14, 71, 13, 57, 12, -53, -86, 53, -44, -35, 2, 127, 12, -66, -44, 46, -115, 3, 10, 56, -35, 119, -19, -61, 52, -59, -127, -49, -23, 4, -5, 17, -82, -6, 127, 25, 79, 67, 64, -25, 14, -64, -37, -127, -28, 21, -63, 66, -53, -41, 109, -62, 15, -22, 13, 29, -63, 20, 27, 95, -44, -59, -116, -10, 79, -49, 22, -43, -16, 46, -47, -120, -36, -29, -52, -44, 29, 127, -13, 49, -9, -127, 75, -28, -23, 88, 59, 11, -95, 81, -59, 58, 60, -26, 40, -92, -3, -22, -58, -45, -59, -22, -53, 71, -29, 66, -32, -23, 14, -17, -66, -24, -28, -62, 47, 38, 17, 16, -37, -24, -11, 8, -27, -19, 59, 45, -49, -47, -4, -22, -81, 30, -67, -127, 74, 102, 5, -18, 98, 34, -66, 42, -52, 7, -59, 24, -58, -19, -24, -118, -73, 91, 15, -16, 79, -32, -79, -127, -36, 41, 77, -83, 2, 56, 22, -75, 127, -16, -21, 12, 31, 56, -113, -127, 90, 55, 61, 12, 55, -14, -113, -14, 32, 49, -67, -17, 91, -10, 1, 21, 69, -70, 99, -19, -112, 66, -90, -10, -9, -71, 127, 50, -81, -49, 24, 61, -61, -111, 7, -41, 127, 88, -66, 108, -127, -6, 36, -14, 41, -50, 14, 14, 73, -101, -28, 77, 127, -8, -100, 88, 38, 121, 88, -125, -60, 13, -94, -115, 20, -67, -87, -94, -119, 44, -28, -30, 18, 5, -53, -61, 20, -43, 11, -77, -60, 13, 29, 3, 6, -72, 38, -60, -11, 108, -53, 41, 66, -12, -127, -127, -49, 24, 29, 46, 36, 91, 34, -33, 116, -51, -34, -52, 91, 7, -83, 73, -26, -103, 24, -10, 76, 84, 5, 68, -80, -13, -17, -32, -48, 20, 50, 26, 10, 63, -104, -14, 37, 127, 114, 97, 35, 1, -33, -55, 127, -124, -33, 61, -7, 119, -32, -127, -53, -42, 63, 3, -5, -26, 70, -58, -33, -44, -43, 34, -56, -127, 127, 25, -35, -11, 16, -81, 29, -58, 40, -127, -127, 20, -47, -11, -36, -63, -52, -32, -82, 78, -76, -73, 8, 27, -72, -9, -74, -85, -86, -57, 25, 78, -10, -97, 35, -65, 8, -59, 14, 1, -42, 32, -88, -44, 17, -3, -9, 59, 40, 12, -108, -40, 24, 34, 18, -28, 2, 51, -110, -4, 100, 1, 65, 22, 0, 127, 61, 45, 25, -31, 6, 9, -7, -48, 99, 16, 44, -2, -40, 32, -39, -52, 10, -110, -19, 56, -127, 69, 26, 51, 92, 40, 61, -52, 45, -38, 13, 85, 122, 27, 66, 45, -111, -83, -3, 31, 37, 19, -36, 58, 71, 39, -78, -47, 58, -78, 8, -62, -36, -14, 61, 42, -127, 71, -4, 24, -54, 52, -127, 67, -4, -42, 30, -63, 59, -3, -1, -18, -46, -92, -81, -96, -14, -53, -10, -11, -77, 13, 1, 8, -67, -127, 127, -28, 26, -14, 18, -13, -26, 2, 10, -46, -32, -15, 27, -31, -59, 59, 77, -121, 28, 40, -54, -62, -31, -21, -37, -32, -6, -127, -25, -60, 70, -127, 112, -127, 127, 88, -7, 116, 110, 53, 87, -127, 3, 16, 23, 74, -106, -51, 3, 74, -82, -112, -74, 65, 81, 25, 53, 127, -45, -50, -103, -41, -65, -29, 79, -67, 64, -33, -30, -8, 127, 0, -13, -51, 67, -14, 5, -92, 29, -35, -8, -90, -57, -3, 36, 43, 44, -31, -69, -7, 36, 39, -51, 43, -81, 58, 6, 127, 12, 57, 66, 46, 59, -43, -42, 41, -15, -120, 24, 3, -11, 19, -13, 51, 28, 3, 55, -48, -12, -1, 2, 97, -19, 29, 42, 13, 43, 78, -44, 56, -108, -43, -19, 127, 15, -11, -18, -81, 83, -37, 77, -109, 15, 65, -50, 43, 12, 13, 27, 28, 61, 57, 30, 26, 106, -18, 56, 13, 97, 4, -8, -62, -103, 94, 108, -44, 52, 27, -47, -9, 105, -53, 46, 89, 103, -33, 38, -34, 55, 51, 70, -94, -35, -87, -107, -19, -31, 9, -19, 79, -14, 77, 5, -19, -107, 85, 21, -45, -39, -42, 9, -29, 74, 47, -75, 60, -127, 120, -112, -57, -32, 41, 7, 79, 76, 66, 57, 41, -25, 31, 37, -47, -36, 43, -73, -37, 63, 127, -69, -52, 90, -33, -61, 60, -55, 44, 15, 4, -67, 13, -92, 64, 29, -39, -3, 83, -2, -38, -85, -86, 58, 35, -69, -61, 29, -37, -95, -78, 4, 30, -4, -32, -80, -22, -9, -77, 46, 7, -93, -71, 65, 9, -50, 127, -70, 26, -12, -39, -114, 63, -127, -100, 4, -32, 111, 22, -60, 65, -101, 26, -42, 21, -59, -27, -74, 2, -94, 6, 126, 5, 76, -88, -9, -43, -101, 127, 1, 125, 92, -63, 52, 56, 4, 81, -127, 127, 80, 127, -29, 30, 116, -74, -17, -57, 105, 48, 45, 25, -72, 48, -38, -108, 31, -34, 4, -11, 41, -127, 52, -104, -43, -37, 52, 2, 47, 87, -9, 77, 27, -41, -25, 90, 86, -56, 75, 10, 33, 78, 58, 127, 127, -7, -73, 49, -33, -106, -35, 38, 57, 53, -17, -4, 83, 52, -108, 54, -125, 28, 23, 56, -43, -88, -17, -6, 47, 23, -9, 0, -13, 111, 75, 27, -52, -38, -34, 39, 30, 66, 39, 38, -64, 38, 3, 21, -32, -51, -28, 54, -38, -87, 20, 52, 115, 18, -81, -70, 0, -14, -46, -46, -3, 125, 16, -14, 23, -82, -84, -69, -20, -65, -127, 9, 81, -49, 61, 7, -36, -45, -42, 57, -26, 47, 20, -85, 46, -13, 41, -37, -75, -60, 86, -78, -127, 12, 50, 2, -3, 13, 47, 5, 19, -78, -55, -27, 65, -71, 12, -108, 20, -16, 11, -31, 63, -55, 37, 75, -17, 127, -73, -33, -28, -120, 105, 68, 106, -103, -106, 71, 61, 2, 23, -3, 33, -5, -15, -67, -15, -23, -54, 15, -63, 76, 58, -110, 1, 83, -27, 22, 75, -39, -17, -11, 64, -17, -127, -54, -66, 31, 96, 116, 3, -114, -7, -108, -63, 97, 9, 50, 8, 75, -28, 72, 112, -36, -112, 95, -50, 23, -13, -19, 55, 21, 23, 92, 91, 22, -49, 16, -75, 23, 9, -49, -97, -37, 49, -36, 36, -127, -86, 43, 127, -24, -24, 84, 83, -35, -34, -12, 109, 102, -38, 51, -68, 34, 19, -22, 49, -32, 127, 40, 24, -93, -4, -3, 105, 3, -58, -18, 8, 127, -18, 125, 68, 69, -62, 30, -36, 54, -57, -24, 17, 43, -36, -27, -57, -67, -21, -10, -49, 68, 12, 65, 4, 48, 55, 127, -75, 44, 89, -66, -13, -78, -82, -91, 22, 30, 33, -40, -87, -34, 96, -91, 39, 10, -64, -3, -12, 127, -50, -37, -56, 23, -35, -36, -54, 90, -91, 2, 50, 77, -6, -127, 16, 46, -5, -73, 0, -56, -18, -72, 28, 93, 60, 49, 20, 18, 111, -111, 32, -83, 47, 47, -10, 35, -88, 43, 57, -98, 127, -17, 0, 1, -39, -127, -2, 0, 63, 93, 0, 36, -66, -61, -19, 39, -127, 58, 50, -17, 127, 88, -43, -108, -51, -16, 7, -36, 68, 46, -14, 107, 40, 57, 7, 19, 8, 3, 88, -90, -92, -18, -21, -24, 13, 7, -4, -78, -91, -4, 8, -35, -5, 19, 2, -111, 4, -66, -81, 122, -20, -34, -37, -84, 127, 68, 46, 17, 47 }; static const uint32_t seedLUT[256] = { 747538460, 1088979410, 1744950180, 1767011913, 1403382928, 521866116, 1060417601, 2110622736, 1557184770, 105289385, 585624216, 1827676546, 1191843873, 1018104344, 1123590530, 663361569, 2023850500, 76561770, 1226763489, 80325252, 1992581442, 502705249, 740409860, 516219202, 557974537, 1883843076, 720112066, 1640137737, 1820967556, 40667586, 155354121, 1820967557, 1115949072, 1631803309, 98284748, 287433856, 2119719977, 988742797, 1827432592, 579378475, 1017745956, 1309377032, 1316535465, 2074315269, 1923385360, 209722667, 1546228260, 168102420, 135274561, 355958469, 248291472, 2127839491, 146920100, 585982612, 1611702337, 696506029, 1386498192, 1258072451, 1212240548, 1043171860, 1217404993, 1090770605, 1386498193, 169093201, 541098240, 1468005469, 456510673, 1578687785, 1838217424, 2010752065, 2089828354, 1362717428, 970073673, 854129835, 714793201, 1266069081, 1047060864, 1991471829, 1098097741, 913883585, 1669598224, 1337918685, 1219264706, 1799741108, 1834116681, 683417731, 1120274457, 1073098457, 1648396544, 176642749, 31171789, 718317889, 1266977808, 1400892508, 549749008, 1808010512, 67112961, 1005669825, 903663673, 1771104465, 1277749632, 1229754427, 950632997, 1979371465, 2074373264, 305357524, 1049387408, 1171033360, 1686114305, 2147468765, 1941195985, 117709841, 809550080, 991480851, 1816248997, 1561503561, 329575568, 780651196, 1659144592, 1910793616, 604016641, 1665084765, 1530186961, 1870928913, 809550081, 2079346113, 71307521, 876663040, 1073807360, 832356664, 1573927377, 204073344, 2026918147, 1702476788, 2043881033, 57949587, 2001393952, 1197426649, 1186508931, 332056865, 950043140, 890043474, 349099312, 148914948, 236204097, 2022643605, 1441981517, 498130129, 1443421481, 924216797, 1817491777, 1913146664, 1411989632, 929068432, 495735097, 1684636033, 1284520017, 432816184, 1344884865, 210843729, 676364544, 234449232, 12112337, 1350619139, 1753272996, 2037118872, 1408560528, 533334916, 1043640385, 357326099, 201376421, 110375493, 541106497, 416159637, 242512193, 777294080, 1614872576, 1535546636, 870600145, 910810409, 1821440209, 1605432464, 1145147393, 951695441, 1758494976, 1506656568, 1557150160, 608221521, 1073840384, 217672017, 684818688, 1750138880, 16777217, 677990609, 953274371, 1770050213, 1359128393, 1797602707, 1984616737, 1865815816, 2120835200, 2051677060, 1772234061, 1579794881, 1652821009, 1742099468, 1887260865, 46468113, 1011925248, 1134107920, 881643832, 1354774993, 472508800, 1892499769, 1752793472, 1962502272, 687898625, 883538000, 1354355153, 1761673473, 944820481, 2020102353, 22020353, 961597696, 1342242816, 964808962, 1355809701, 17016649, 1386540177, 647682692, 1849012289, 751668241, 1557184768, 127374604, 1927564752, 1045744913, 1614921984, 43588881, 1016185088, 1544617984, 1090519041, 136122424, 215038417, 1563027841, 2026918145, 1688778833, 701530369, 1372639488, 1342242817, 2036945104, 953274369, 1750192384, 16842753, 964808960, 1359020032, 1358954497 }; static const uint32_t deblockFactor[13] = { 64, 71, 77, 84, 90, 96, 103, 109, 116, 122, 128, 128, 128 }; SEIFilmGrainSynthesizer::SEIFilmGrainSynthesizer() : m_width (0) , m_height (0) , m_chromaFormat (NUM_CHROMA_FORMAT) , m_bitDepth (0) , m_idrPicId (0) , m_grainSynt (NULL) , m_fgsBlkSize (8) , m_poc (0) , m_errorCode (0) , m_fgcParameters (NULL) { } void SEIFilmGrainSynthesizer::create(uint32_t width, uint32_t height, ChromaFormat fmt, uint8_t bitDepth, uint32_t idrPicId) { m_width = width; m_height = height; m_chromaFormat = fmt; m_bitDepth = bitDepth; m_idrPicId = idrPicId; m_fgsBlkSize = 8; m_errorCode = 0; if (!m_grainSynt) m_grainSynt = new GrainSynthesisStruct; if (!m_fgcParameters) m_fgcParameters = new SEIFilmGrainCharacteristics; } SEIFilmGrainSynthesizer::~SEIFilmGrainSynthesizer() { destroy(); } void SEIFilmGrainSynthesizer::fgsInit() { deriveFGSBlkSize(); dataBaseGen(); } void SEIFilmGrainSynthesizer::destroy() { if (m_fgcParameters) delete m_fgcParameters; if (m_grainSynt) delete m_grainSynt; } void SEIFilmGrainSynthesizer::grainSynthesizeAndBlend(PelStorage* pGrainBuf, bool isIdrPic) { uint8_t numComp = MAX_NUM_COMPONENT, compCtr; /* number of color components */ uint8_t color_offset[MAX_NUM_COMPONENT]; uint32_t widthComp[MAX_NUM_COMPONENT], heightComp[MAX_NUM_COMPONENT], strideComp[MAX_NUM_COMPONENT]; uint32_t * offsetsArr[MAX_NUM_COMPONENT]; Pel * decComp[MAX_NUM_COMPONENT]; uint32_t pseudoRandValEc; uint32_t picOffset; /* from SMPTE RDD5 */ color_offset[0] = COLOUR_OFFSET_LUMA; color_offset[1] = COLOUR_OFFSET_CR; color_offset[2] = COLOUR_OFFSET_CB; if (0 != m_fgcParameters->m_filmGrainCharacteristicsCancelFlag) { return; } widthComp[0] = m_width; heightComp[0] = m_height; if (CHROMA_420 == m_chromaFormat) { widthComp[1] = (m_width >> 1); widthComp[2] = (m_width >> 1); heightComp[1] = (m_height >> 1); heightComp[2] = (m_height >> 1); } else if (CHROMA_422 == m_chromaFormat) { widthComp[1] = (m_width >> 1); widthComp[2] = (m_width >> 1); heightComp[1] = m_height; heightComp[2] = m_height; } else if (CHROMA_400 == m_chromaFormat) { numComp = 1; } /*Allocate memory for offsets assuming 16x16 block size, 32x32 will need lesser than this*/ uint32_t maxNumBlocks = ((m_width >> 4) + 1) * ((m_height >> 4) + 1); for (compCtr = 0; compCtr < numComp; compCtr++) { offsetsArr[compCtr] = new uint32_t[maxNumBlocks]; } /*decComp[0] = pGrainBuf->getOrigin(COMPONENT_Y); decComp[1] = pGrainBuf->getOrigin(COMPONENT_Cb); decComp[2] = pGrainBuf->getOrigin(COMPONENT_Cb);*/ decComp[0] = pGrainBuf->bufs[0].buf; decComp[1] = pGrainBuf->bufs[1].buf; decComp[2] = pGrainBuf->bufs[2].buf; /* component strides */ strideComp[0] = pGrainBuf->bufs[0].stride; strideComp[1] = 0; strideComp[2] = 0; if (CHROMA_400 != m_chromaFormat) { strideComp[1] = pGrainBuf->bufs[1].stride; strideComp[2] = pGrainBuf->bufs[2].stride; } int32_t numBlks_x[MAX_NUM_COMPONENT]; int32_t numBlks_y[MAX_NUM_COMPONENT]; picOffset = m_poc; for (compCtr = 0; compCtr < numComp; compCtr++) { if (BLK_32 == m_fgsBlkSize) { numBlks_x[compCtr] = (widthComp[compCtr] >> 5) + ((widthComp[compCtr] & 0x1F) ? 1 : 0); numBlks_y[compCtr] = (heightComp[compCtr] >> 5) + ((heightComp[compCtr] & 0x1F) ? 1 : 0); } else { numBlks_x[compCtr] = (widthComp[compCtr] >> 4) + ((widthComp[compCtr] & 0xF) ? 1 : 0); numBlks_y[compCtr] = (heightComp[compCtr] >> 4) + ((heightComp[compCtr] & 0xF) ? 1 : 0); } } for (compCtr = 0; compCtr < numComp; compCtr++) { if (1 == m_fgcParameters->m_compModel[compCtr].presentFlag) { uint32_t *tmp = offsetsArr[compCtr]; int i, j; /* Seed initialization for current picture*/ pseudoRandValEc = seedLUT[((picOffset + color_offset[compCtr]) & 0xFF)]; for (i = 0; i < numBlks_y[compCtr]; i++) { for (j = 0; j < numBlks_x[compCtr]; j++) { *tmp = pseudoRandValEc; pseudoRandValEc = prng(pseudoRandValEc); tmp++; } } } } m_fgsArgs.numComp = numComp; for (compCtr = 0; compCtr < numComp; compCtr++) { if (1 == m_fgcParameters->m_compModel[compCtr].presentFlag) { m_fgsArgs.decComp[compCtr] = decComp[compCtr]; m_fgsArgs.widthComp[compCtr] = widthComp[compCtr]; m_fgsArgs.strideComp[compCtr] = strideComp[compCtr]; m_fgsArgs.fgsOffsets[compCtr] = offsetsArr[compCtr]; if (BLK_32 == m_fgsBlkSize) { m_fgsArgs.heightComp[compCtr] = numBlks_y[compCtr] * BLK_32; } else { m_fgsArgs.heightComp[compCtr] = numBlks_y[compCtr] * BLK_16; } } } m_fgsArgs.pFgcParameters = m_fgcParameters; m_fgsArgs.blkSize = m_fgsBlkSize; m_fgsArgs.bitDepth = m_bitDepth; m_fgsArgs.pGrainSynt = m_grainSynt; fgsProcess(m_fgsArgs); for (compCtr = 0; compCtr < numComp; compCtr++) { delete offsetsArr[compCtr]; } return; } /* Function validates film grain parameters and returns 0 for valid parameters of SMPTE-RDD5 else 1*/ /* Also down converts the chroma model values for 4:2:0 and 4:2:2 chroma_formats */ uint8_t SEIFilmGrainSynthesizer::grainValidateParams() { uint8_t numComp = MAX_NUM_COMPONENT; /* number of color components */ uint8_t compCtr, intensityCtr, multiGrainCheck[MAX_NUM_COMPONENT][MAX_NUM_INTENSITIES] = { { 0 } }; uint16_t multiGrainCtr; uint8_t limitCompModelVal1[10] = { 0 }, limitCompModelVal2[10] = { 0 }; uint8_t num_comp_model_pairs = 0, limitCompModelCtr, compPairMatch; memset(m_grainSynt->intensityInterval, INTENSITY_INTERVAL_MATCH_FAIL, sizeof(m_grainSynt->intensityInterval)); if ((m_width < MIN_WIDTH) || (m_width > MAX_WIDTH) || (m_width % 4)) { return FGS_INVALID_WIDTH; /* Width not supported */ } if ((m_height < MIN_HEIGHT) || (m_height > MAX_HEIGHT) || (m_height % 4)) { return FGS_INVALID_HEIGHT; /* Height not supported */ } if ((m_chromaFormat < MIN_CHROMA_FORMAT_IDC) || (m_chromaFormat > MAX_CHROMA_FORMAT_IDC)) { return FGS_INVALID_CHROMA_FORMAT; /* Chroma format not supported */ } if (m_chromaFormat == MIN_CHROMA_FORMAT_IDC) /* Mono Chrome */ { numComp = 1; } if ((m_bitDepth < MIN_BIT_DEPTH) || (m_bitDepth > MAX_BIT_DEPTH)) { return FGS_INVALID_BIT_DEPTH; /* Bit depth not supported */ } if ((0 != m_fgcParameters->m_filmGrainCharacteristicsCancelFlag) && (1 != m_fgcParameters->m_filmGrainCharacteristicsCancelFlag)) { return FGS_INVALID_FGC_CANCEL_FLAG; /* Film grain synthesis disabled */ } if (FILM_GRAIN_MODEL_ID_VALUE != m_fgcParameters->m_filmGrainModelId) { return FGS_INVALID_GRAIN_MODEL_ID; /* Not supported */ } if (0 != m_fgcParameters->m_separateColourDescriptionPresentFlag) { return FGS_INVALID_SEP_COL_DES_FLAG; /* Not supported */ } if (BLENDING_MODE_VALUE != m_fgcParameters->m_blendingModeId) { return FGS_INVALID_BLEND_MODE; /* Not supported */ } if (m_fgcParameters->m_compModel[0].presentFlag || m_fgcParameters->m_compModel[1].presentFlag || m_fgcParameters->m_compModel[2].presentFlag) { if ((m_fgcParameters->m_log2ScaleFactor < MIN_LOG2SCALE_VALUE) || (m_fgcParameters->m_log2ScaleFactor > MAX_LOG2SCALE_VALUE)) { return FGS_INVALID_LOG2_SCALE_FACTOR; /* Not supported */ } } /* validation of component model present flag */ for (compCtr = 0; compCtr < numComp; compCtr++) { if ((m_fgcParameters->m_compModel[compCtr].presentFlag != true) && (m_fgcParameters->m_compModel[compCtr].presentFlag != false)) { return FGS_INVALID_COMP_MODEL_PRESENT_FLAG; /* Not supported */ } if (m_fgcParameters->m_compModel[compCtr].presentFlag && (m_fgcParameters->m_compModel[compCtr].numModelValues > MAX_ALLOWED_MODEL_VALUES)) { return FGS_INVALID_NUM_MODEL_VALUES; /* Not supported */ } } /* validation of intensity intervals and */ for (compCtr = 0; compCtr < numComp; compCtr++) { if (m_fgcParameters->m_compModel[compCtr].presentFlag) { for (intensityCtr = 0; intensityCtr < m_fgcParameters->m_compModel[compCtr].intensityValues.size(); intensityCtr++) { if (m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].intensityIntervalLowerBound > m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].intensityIntervalUpperBound) { return FGS_INVALID_INTENSITY_BOUNDARY_VALUES; /* Not supported */ } for (multiGrainCtr = m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].intensityIntervalLowerBound; multiGrainCtr <= m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].intensityIntervalUpperBound; multiGrainCtr++) { m_grainSynt->intensityInterval[compCtr][multiGrainCtr] = intensityCtr; if (multiGrainCheck[compCtr][multiGrainCtr]) /* Non over lap */ { return FGS_INVALID_INTENSITY_BOUNDARY_VALUES; /* Not supported */ } else { multiGrainCheck[compCtr][multiGrainCtr] = 1; } } m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue.resize(MAX_NUM_MODEL_VALUES); /* default initialization for cut off frequencies */ if (1 == m_fgcParameters->m_compModel[compCtr].numModelValues) { m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[1] = DEFAULT_HORZ_CUT_OFF_FREQUENCY; m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[2] = m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[1]; } else if (2 == m_fgcParameters->m_compModel[compCtr].numModelValues) { m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[2] = m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[1]; } /* Error check on model component value */ if (m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[0] > (MAX_STANDARD_DEVIATION << (m_bitDepth - BIT_DEPTH_8))) { return FGS_INVALID_STANDARD_DEVIATION; /* Not supported */ } else if ((m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[1] < MIN_CUT_OFF_FREQUENCY) || (m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[1] > MAX_CUT_OFF_FREQUENCY)) { return FGS_INVALID_CUT_OFF_FREQUENCIES; /* Not supported */ } else if ((m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[2] < MIN_CUT_OFF_FREQUENCY) || (m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[2] > MAX_CUT_OFF_FREQUENCY)) { return FGS_INVALID_CUT_OFF_FREQUENCIES; /* Not supported */ } /* conversion of component model values for 4:2:0 and 4:4:4 */ if (CHROMA_444 != m_chromaFormat && (compCtr > 0)) { if (CHROMA_420 == m_chromaFormat) /* 4:2:0 */ { m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[0] >>= 1; m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[1] = CLIP3(MIN_CUT_OFF_FREQUENCY, MAX_CUT_OFF_FREQUENCY, (m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[1] << 1)); m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[2] = CLIP3(MIN_CUT_OFF_FREQUENCY, MAX_CUT_OFF_FREQUENCY, (m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[2] << 1)); } else if (CHROMA_422 == m_chromaFormat)/* 4:2:2 */ { m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[0] = (m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[0] * SCALE_DOWN_422) >> Q_FORMAT_SCALING; m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[1] = CLIP3(MIN_CUT_OFF_FREQUENCY, MAX_CUT_OFF_FREQUENCY, (m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[1] << 1)); } } compPairMatch = 0; for (limitCompModelCtr = 0; limitCompModelCtr <= num_comp_model_pairs; limitCompModelCtr++) { if ((limitCompModelVal1[limitCompModelCtr] == m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[1]) && (limitCompModelVal2[limitCompModelCtr] == m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[2])) { compPairMatch = 1; } } if (0 == compPairMatch) { num_comp_model_pairs++; /* max allowed pairs are 10 as per SMPTE -RDD5*/ if (num_comp_model_pairs > MAX_ALLOWED_COMP_MODEL_PAIRS) { return FGS_INVALID_NUM_CUT_OFF_FREQ_PAIRS; /* Not supported */ } limitCompModelVal1[num_comp_model_pairs - 1] = m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[1]; limitCompModelVal2[num_comp_model_pairs - 1] = m_fgcParameters->m_compModel[compCtr].intensityValues[intensityCtr].compModelValue[2]; } } } } return FGS_SUCCESS; /* Success */ } void SEIFilmGrainSynthesizer::deriveFGSBlkSize() { uint32_t picSizeInLumaSamples = m_height * m_width; if (picSizeInLumaSamples <= (1920 * 1080)) { m_fgsBlkSize = BLK_8; } else if (picSizeInLumaSamples <= (3840 * 2160)) { m_fgsBlkSize = BLK_16; } else { m_fgsBlkSize = BLK_32; } } void SEIFilmGrainSynthesizer::dataBaseGen() { uint32_t pseudoRandValEhv; uint8_t h, v; /* Horizaontal and vertical cut off frequencies (+2)*/ uint32_t ScaleCutOffFh, ScaleCutOffFv, l, r, i, j, k; int32_t B[DATA_BASE_SIZE][DATA_BASE_SIZE], IDCT[DATA_BASE_SIZE][DATA_BASE_SIZE]; int32_t Grain[DATA_BASE_SIZE][DATA_BASE_SIZE]; const TMatrixCoeff* Tmp = g_trCoreDCT2P64[TRANSFORM_FORWARD][0]; const int transform_scale = 9; // upscaling of original transform as specified in VVC (for 64x64 block) const int add_1st = 1 << (transform_scale - 1); TMatrixCoeff T[DATA_BASE_SIZE][DATA_BASE_SIZE]; // Original TMatrixCoeff TT[DATA_BASE_SIZE][DATA_BASE_SIZE]; // Transpose for (int x = 0; x < DATA_BASE_SIZE; x++) { for (int y = 0; y < DATA_BASE_SIZE; y++) { T[x][y] = Tmp[x * 64 + y]; /* Matrix Original */ TT[y][x] = Tmp[x * 64 + y]; /* Matrix Transpose */ } } for (h = 0; h < NUM_CUT_OFF_FREQ; h++) { for (v = 0; v < NUM_CUT_OFF_FREQ; v++) { memset(&B, 0, DATA_BASE_SIZE*DATA_BASE_SIZE * sizeof(int32_t)); memset(&IDCT, 0, DATA_BASE_SIZE*DATA_BASE_SIZE * sizeof(int32_t)); memset(&Grain, 0, DATA_BASE_SIZE*DATA_BASE_SIZE * sizeof(int32_t)); ScaleCutOffFh = ((h + 3) << 2) - 1; ScaleCutOffFv = ((v + 3) << 2) - 1; /* ehv : seed to be used for the psudo random generator for a given h and v */ pseudoRandValEhv = seedLUT[h + v * 13]; for (l = 0, r = 0; l <= ScaleCutOffFv; l++) { for (k = 0; k <= ScaleCutOffFh; k += 4) { B[k][l] = gaussianLUT[pseudoRandValEhv % 2048]; B[k + 1][l] = gaussianLUT[(pseudoRandValEhv + 1) % 2048]; B[k + 2][l] = gaussianLUT[(pseudoRandValEhv + 2) % 2048]; B[k + 3][l] = gaussianLUT[(pseudoRandValEhv + 3) % 2048]; r++; pseudoRandValEhv = prng(pseudoRandValEhv); } } B[0][0] = 0; for (i = 0; i < DATA_BASE_SIZE; i++) { for (j = 0; j < DATA_BASE_SIZE; j++) { for (k = 0; k < DATA_BASE_SIZE; k++) { IDCT[i][j] += TT[i][k] * B[k][j]; } IDCT[i][j] += add_1st; IDCT[i][j] = IDCT[i][j] >> transform_scale; } } for (i = 0; i < DATA_BASE_SIZE; i++) { for (j = 0; j < DATA_BASE_SIZE; j++) { for (k = 0; k < DATA_BASE_SIZE; k++) { Grain[i][j] += IDCT[i][k] * T[k][j]; } Grain[i][j] += add_1st; Grain[i][j] = Grain[i][j] >> transform_scale; m_grainSynt->dataBase[h][v][j][i] = CLIP3(-127, 127, Grain[i][j]); } } /* De-blocking at horizontal block edges */ for (l = 0; l < DATA_BASE_SIZE; l += m_fgsBlkSize) { for (k = 0; k < DATA_BASE_SIZE; k++) { m_grainSynt->dataBase[h][v][l][k] = ((m_grainSynt->dataBase[h][v][l][k]) * deblockFactor[v]) >> 7; m_grainSynt->dataBase[h][v][l + m_fgsBlkSize - 1][k] = ((m_grainSynt->dataBase[h][v][l + m_fgsBlkSize - 1][k]) * deblockFactor[v]) >> 7; } } } } return; } uint32_t SEIFilmGrainSynthesizer::prng(uint32_t x_r) { uint32_t addVal; addVal = (1 + ((x_r & (POS_2)) > 0) + ((x_r & (POS_30)) > 0)) % 2; x_r = (x_r << 1) + addVal; return x_r; } uint32_t SEIFilmGrainSynthesizer::fgsProcess(fgsProcessArgs &inArgs) { uint32_t errorCode; uint8_t blkSize = inArgs.blkSize; if (blkSize == 8) errorCode = fgsSimulationBlending_8x8(&inArgs); else if (blkSize == 16) errorCode = fgsSimulationBlending_16x16(&inArgs); else if (blkSize == 32) errorCode = fgsSimulationBlending_32x32(&inArgs); else errorCode = FGS_FAIL; return errorCode; } void SEIFilmGrainSynthesizer::deblockGrainStripe(Pel *grainStripe, uint32_t widthComp, uint32_t heightComp, uint32_t strideComp, uint32_t blkSize) { int32_t left1, left0, right0, right1; uint32_t pos, vertCtr; uint32_t widthCropped = (widthComp - blkSize); for (vertCtr = 0; vertCtr < heightComp; vertCtr++) { for (pos = 0; pos < widthCropped; pos += blkSize) { left1 = *(grainStripe + blkSize - 2); left0 = *(grainStripe + blkSize - 1); right0 = *(grainStripe + blkSize + 0); right1 = *(grainStripe + blkSize + 1); *(grainStripe + blkSize + 0) = (left0 + (right0 << 1) + right1) >> 2; *(grainStripe + blkSize - 1) = (left1 + (left0 << 1) + right0) >> 2; grainStripe += blkSize; } grainStripe = grainStripe + (strideComp - pos); } return; } void SEIFilmGrainSynthesizer::blendStripe(Pel *decSampleHbdOffsetY, Pel *grainStripe, uint32_t widthComp, uint32_t strideSrc, uint32_t strideGrain, uint32_t blockHeight, uint8_t bitDepth) { uint32_t k, l; uint16_t maxRange; maxRange = (1 << bitDepth) - 1; int32_t grainSample; uint16_t decodeSampleHbd; uint8_t bitDepthShift = (bitDepth - BIT_DEPTH_8); uint32_t bufInc = (strideSrc - widthComp); uint32_t grainBufInc = (strideGrain - widthComp); for (l = 0; l < blockHeight; l++) /* y direction */ { for (k = 0; k < widthComp; k++) /* x direction */ { decodeSampleHbd = *decSampleHbdOffsetY; grainSample = *grainStripe; grainSample <<= bitDepthShift; grainSample = CLIP3(0, maxRange, grainSample + decodeSampleHbd); *decSampleHbdOffsetY = (Pel)grainSample; decSampleHbdOffsetY++; grainStripe++; } decSampleHbdOffsetY += bufInc; grainStripe += grainBufInc; } return; } void SEIFilmGrainSynthesizer::blendStripe_32x32(Pel *decSampleHbdOffsetY, Pel *grainStripe, uint32_t widthComp, uint32_t strideSrc, uint32_t strideGrain, uint32_t blockHeight, uint8_t bitDepth) { uint32_t k, l; uint16_t maxRange; maxRange = (1 << bitDepth) - 1; int32_t grainSample; uint16_t decodeSampleHbd; uint8_t bitDepthShift = (bitDepth - BIT_DEPTH_8); uint32_t bufInc = (strideSrc - widthComp); uint32_t grainBufInc = (strideGrain - widthComp); for (l = 0; l < blockHeight; l++) /* y direction */ { for (k = 0; k < widthComp; k++) /* x direction */ { decodeSampleHbd = *decSampleHbdOffsetY; grainSample = *grainStripe; grainSample <<= bitDepthShift; grainSample = CLIP3(0, maxRange, grainSample + decodeSampleHbd); *decSampleHbdOffsetY = (Pel)grainSample; decSampleHbdOffsetY++; grainStripe++; } decSampleHbdOffsetY += bufInc; grainStripe += grainBufInc; } return; } Pel SEIFilmGrainSynthesizer::blockAverage_8x8(Pel *decSampleBlk8, uint32_t widthComp, uint16_t *pNumSamples, uint8_t ySize, uint8_t xSize, uint8_t bitDepth) { uint32_t blockAvg = 0; uint8_t k; uint8_t l; for (k = 0; k < ySize; k++) { for (l = 0; l < xSize; l++) { blockAvg += *decSampleBlk8; decSampleBlk8++; } decSampleBlk8 += widthComp - xSize; } blockAvg = blockAvg >> (BLK_8_shift + (bitDepth - BIT_DEPTH_8)); *pNumSamples = BLK_AREA_8x8; return blockAvg; } uint32_t SEIFilmGrainSynthesizer::blockAverage_16x16(Pel *decSampleBlk8, uint32_t widthComp, uint16_t *pNumSamples, uint8_t ySize, uint8_t xSize, uint8_t bitDepth) { uint32_t blockAvg = 0; uint8_t k; uint8_t l; for (k = 0; k < ySize; k++) { for (l = 0; l < xSize; l++) { blockAvg += *decSampleBlk8; decSampleBlk8++; } decSampleBlk8 += widthComp - xSize; } // blockAvg = blockAvg >> (BLK_16_shift + (bitDepth - BIT_DEPTH_8)); // If BLK_16 is not used or changed BLK_AREA_16x16 has to be changed *pNumSamples = BLK_AREA_16x16; return blockAvg; } uint32_t SEIFilmGrainSynthesizer::blockAverage_32x32(Pel *decSampleBlk32, uint32_t strideComp, uint8_t bitDepth) { uint32_t blockAvg = 0; uint8_t k; uint8_t l; uint32_t bufInc = strideComp - BLK_32; for (k = 0; k < BLK_32; k++) { for (l = 0; l < BLK_32; l++) { blockAvg += *decSampleBlk32++; } decSampleBlk32 += bufInc; } blockAvg = blockAvg >> (BLK_32_shift + (bitDepth - BIT_DEPTH_8)); return blockAvg; } void SEIFilmGrainSynthesizer::simulateGrainBlk8x8(Pel *grainStripe, uint32_t grainStripeOffsetBlk8, GrainSynthesisStruct *grain_synt, uint32_t width, uint8_t log2ScaleFactor, int16_t scaleFactor, uint32_t kOffset, uint32_t lOffset, uint8_t h, uint8_t v, uint32_t xSize) { uint32_t l; int8_t * database_h_v = &grain_synt->dataBase[h][v][lOffset][kOffset]; grainStripe += grainStripeOffsetBlk8; uint32_t k; for (l = 0; l < BLK_8; l++) /* y direction */ { for (k = 0; k < xSize; k++) /* x direction */ { *grainStripe = ((scaleFactor * (*database_h_v)) >> (log2ScaleFactor + GRAIN_SCALE)); grainStripe++; database_h_v++; } grainStripe += width - xSize; database_h_v += DATA_BASE_SIZE - xSize; } return; } void SEIFilmGrainSynthesizer::simulateGrainBlk16x16(Pel *grainStripe, uint32_t grainStripeOffsetBlk8, GrainSynthesisStruct *grain_synt, uint32_t width, uint8_t log2ScaleFactor, int16_t scaleFactor, uint32_t kOffset, uint32_t lOffset, uint8_t h, uint8_t v, uint32_t xSize) { uint32_t l; int8_t * database_h_v = &grain_synt->dataBase[h][v][lOffset][kOffset]; grainStripe += grainStripeOffsetBlk8; uint32_t k; for (l = 0; l < BLK_16; l++) /* y direction */ { for (k = 0; k < xSize; k++) /* x direction */ { *grainStripe = (int16_t)(((int32_t)scaleFactor * (*database_h_v)) >> (log2ScaleFactor + GRAIN_SCALE)); grainStripe++; database_h_v++; } grainStripe += width - xSize; database_h_v += DATA_BASE_SIZE - xSize; } return; } void SEIFilmGrainSynthesizer::simulateGrainBlk32x32(Pel *grainStripe, uint32_t grainStripeOffsetBlk32, GrainSynthesisStruct *grain_synt, uint32_t width, uint8_t log2ScaleFactor, int16_t scaleFactor, uint32_t kOffset, uint32_t lOffset, uint8_t h, uint8_t v) { uint32_t l; int8_t * database_h_v = &grain_synt->dataBase[h][v][lOffset][kOffset]; grainStripe += grainStripeOffsetBlk32; uint32_t k; uint8_t shiftVal = log2ScaleFactor + GRAIN_SCALE; uint32_t grainbufInc = width - BLK_32; for (l = 0; l < BLK_32; l++) /* y direction */ { for (k = 0; k < BLK_32; k++) /* x direction */ { *grainStripe = ((scaleFactor * (*database_h_v)) >> shiftVal); grainStripe++; database_h_v++; } grainStripe += grainbufInc; database_h_v += DATA_BASE_SIZE - BLK_32; } return; } uint32_t SEIFilmGrainSynthesizer::fgsSimulationBlending_8x8(fgsProcessArgs *inArgs) { uint8_t numComp, compCtr, blkId; /* number of color components */ uint8_t log2ScaleFactor, h, v; uint8_t bitDepth; /*grain bit depth and decoded bit depth are assumed to be same */ uint32_t widthComp[MAX_NUM_COMPONENT], heightComp[MAX_NUM_COMPONENT], strideComp[MAX_NUM_COMPONENT]; Pel * decSampleHbdBlk16, *decSampleHbdBlk8, *decSampleHbdOffsetY; Pel * decHbdComp[MAX_NUM_COMPONENT]; uint16_t numSamples; int16_t scaleFactor; uint32_t kOffset, lOffset, grainStripeOffset, grainStripeOffsetBlk8, offsetBlk8x8; uint32_t kOffset_const, lOffset_const; int16_t scaleFactor_const; Pel * grainStripe; /* worth a row of 16x16 : Max size : 16xw;*/ int32_t yOffset8x8, xOffset8x8; uint32_t x, y; uint32_t blockAvg, intensityInt; /* ec : seed to be used for the psudo random generator for a given color component */ uint32_t grainStripeWidth; uint32_t wdPadded; bitDepth = inArgs->bitDepth; numComp = inArgs->numComp; log2ScaleFactor = inArgs->pFgcParameters->m_log2ScaleFactor; for (compCtr = 0; compCtr < numComp; compCtr++) { decHbdComp[compCtr] = inArgs->decComp[compCtr]; strideComp[compCtr] = inArgs->strideComp[compCtr]; widthComp[compCtr] = inArgs->widthComp[compCtr]; heightComp[compCtr] = inArgs->heightComp[compCtr]; } wdPadded = ((inArgs->widthComp[0] - 1) | 0xF) + 1; grainStripe = new Pel[wdPadded * BLK_16]; if (0 == inArgs->pFgcParameters->m_filmGrainCharacteristicsCancelFlag) { for (compCtr = 0; compCtr < numComp; compCtr++) { if (1 == inArgs->pFgcParameters->m_compModel[compCtr].presentFlag) { decSampleHbdOffsetY = decHbdComp[compCtr]; uint32_t *offset_tmp = inArgs->fgsOffsets[compCtr]; grainStripeWidth = ((widthComp[compCtr] - 1) | 0xF) + 1; // Make next muliptle of 16 /* Loop of 16x16 blocks */ for (y = 0; y < heightComp[compCtr]; y += BLK_16) { /* Initialization of grain stripe of 16xwidth size */ memset(grainStripe, 0, (grainStripeWidth * BLK_16 * sizeof(Pel))); for (x = 0; x < widthComp[compCtr]; x += BLK_16) { /* start position offset of decoded sample in x direction */ grainStripeOffset = x; decSampleHbdBlk16 = decSampleHbdOffsetY + x; kOffset_const = (MSB16(*offset_tmp) % 52); kOffset_const &= 0xFFFC; lOffset_const = (LSB16(*offset_tmp) % 56); lOffset_const &= 0xFFF8; scaleFactor_const = 1 - 2 * BIT0(*offset_tmp); for (blkId = 0; blkId < NUM_8x8_BLKS_16x16; blkId++) { yOffset8x8 = (blkId >> 1) * BLK_8; xOffset8x8 = (blkId & 0x1) * BLK_8; offsetBlk8x8 = xOffset8x8 + (yOffset8x8 * strideComp[compCtr]); grainStripeOffsetBlk8 = grainStripeOffset + (xOffset8x8 + (yOffset8x8 * grainStripeWidth)); decSampleHbdBlk8 = decSampleHbdBlk16 + offsetBlk8x8; blockAvg = blockAverage_8x8(decSampleHbdBlk8, strideComp[compCtr], &numSamples, BLK_8, BLK_8, bitDepth); /* Selection of the component model */ intensityInt = inArgs->pGrainSynt->intensityInterval[compCtr][blockAvg]; if (INTENSITY_INTERVAL_MATCH_FAIL != intensityInt) { /* 8x8 grain block offset using co-ordinates of decoded 8x8 block in the frame */ // kOffset = kOffset_const; kOffset = kOffset_const + xOffset8x8; lOffset = lOffset_const + yOffset8x8; scaleFactor = scaleFactor_const * inArgs->pFgcParameters->m_compModel[compCtr].intensityValues[intensityInt].compModelValue[0]; h = inArgs->pFgcParameters->m_compModel[compCtr].intensityValues[intensityInt].compModelValue[1] - 2; v = inArgs->pFgcParameters->m_compModel[compCtr].intensityValues[intensityInt].compModelValue[2] - 2; /* 8x8 block grain simulation */ simulateGrainBlk8x8(grainStripe, grainStripeOffsetBlk8, inArgs->pGrainSynt, grainStripeWidth, log2ScaleFactor, scaleFactor, kOffset, lOffset, h, v, BLK_8); } /* only if average falls in any interval */ // }/* includes corner case handling */ } /* 8x8 level block processing */ /* uppdate the PRNG once per 16x16 block of samples */ offset_tmp++; } /* End of 16xwidth grain simulation */ /* deblocking at the vertical edges of 8x8 at 16xwidth*/ deblockGrainStripe(grainStripe, widthComp[compCtr], BLK_16, grainStripeWidth, BLK_8); /* Blending of size 16xwidth*/ blendStripe(decSampleHbdOffsetY, grainStripe, widthComp[compCtr], strideComp[compCtr], grainStripeWidth, BLK_16, bitDepth); decSampleHbdOffsetY += BLK_16 * strideComp[compCtr]; } /* end of component loop */ } } } delete grainStripe; return FGS_SUCCESS; } uint32_t SEIFilmGrainSynthesizer::fgsSimulationBlending_16x16(fgsProcessArgs *inArgs) { uint8_t numComp, compCtr; /* number of color components */ uint8_t log2ScaleFactor, h, v; uint8_t bitDepth; /*grain bit depth and decoded bit depth are assumed to be same */ uint32_t widthComp[MAX_NUM_COMPONENT], heightComp[MAX_NUM_COMPONENT], strideComp[MAX_NUM_COMPONENT]; Pel * decSampleHbdBlk16, *decSampleHbdOffsetY; Pel * decHbdComp[MAX_NUM_COMPONENT]; uint16_t numSamples; int16_t scaleFactor; uint32_t kOffset, lOffset, grainStripeOffset; Pel * grainStripe; /* worth a row of 16x16 : Max size : 16xw;*/ uint32_t x, y; uint32_t blockAvg, intensityInt; /* ec : seed to be used for the psudo random generator for a given color component */ uint32_t grainStripeWidth; uint32_t wdPadded; bitDepth = inArgs->bitDepth; numComp = inArgs->numComp; log2ScaleFactor = inArgs->pFgcParameters->m_log2ScaleFactor; for (compCtr = 0; compCtr < numComp; compCtr++) { decHbdComp[compCtr] = inArgs->decComp[compCtr]; strideComp[compCtr] = inArgs->strideComp[compCtr]; widthComp[compCtr] = inArgs->widthComp[compCtr]; heightComp[compCtr] = inArgs->heightComp[compCtr]; } wdPadded = ((inArgs->widthComp[0] - 1) | 0xF) + 1; grainStripe = new Pel[wdPadded * BLK_16]; if (0 == inArgs->pFgcParameters->m_filmGrainCharacteristicsCancelFlag) { for (compCtr = 0; compCtr < numComp; compCtr++) { if (1 == inArgs->pFgcParameters->m_compModel[compCtr].presentFlag) { decSampleHbdOffsetY = decHbdComp[compCtr]; uint32_t *offset_tmp = inArgs->fgsOffsets[compCtr]; grainStripeWidth = ((widthComp[compCtr] - 1) | 0xF) + 1; // Make next muliptle of 16 /* Loop of 16x16 blocks */ for (y = 0; y < heightComp[compCtr]; y += BLK_16) { /* Initialization of grain stripe of 16xwidth size */ memset(grainStripe, 0, (grainStripeWidth * BLK_16 * sizeof(Pel))); for (x = 0; x < widthComp[compCtr]; x += BLK_16) { /* start position offset of decoded sample in x direction */ grainStripeOffset = x; decSampleHbdBlk16 = decSampleHbdOffsetY + x; blockAvg = blockAverage_16x16(decSampleHbdBlk16, strideComp[compCtr], &numSamples, BLK_16, BLK_16, bitDepth); blockAvg = blockAvg >> (BLK_16_shift + (bitDepth - BIT_DEPTH_8)); /* Selection of the component model */ intensityInt = inArgs->pGrainSynt->intensityInterval[compCtr][blockAvg]; if (INTENSITY_INTERVAL_MATCH_FAIL != intensityInt) { kOffset = (MSB16(*offset_tmp) % 52); kOffset &= 0xFFFC; lOffset = (LSB16(*offset_tmp) % 56); lOffset &= 0xFFF8; scaleFactor = 1 - 2 * BIT0(*offset_tmp); scaleFactor *= inArgs->pFgcParameters->m_compModel[compCtr].intensityValues[intensityInt].compModelValue[0]; h = inArgs->pFgcParameters->m_compModel[compCtr].intensityValues[intensityInt].compModelValue[1] - 2; v = inArgs->pFgcParameters->m_compModel[compCtr].intensityValues[intensityInt].compModelValue[2] - 2; /* 16x16 block grain simulation */ simulateGrainBlk16x16(grainStripe, grainStripeOffset, inArgs->pGrainSynt, grainStripeWidth, log2ScaleFactor, scaleFactor, kOffset, lOffset, h, v, BLK_16); } /* only if average falls in any interval */ // }/* includes corner case handling */ /* uppdate the PRNG once per 16x16 block of samples */ offset_tmp++; } /* End of 16xwidth grain simulation */ /* deblocking at the vertical edges of 16x16 at 16xwidth*/ deblockGrainStripe(grainStripe, widthComp[compCtr], BLK_16, grainStripeWidth, BLK_16); /* Blending of size 16xwidth*/ blendStripe(decSampleHbdOffsetY, grainStripe, widthComp[compCtr], strideComp[compCtr], grainStripeWidth, BLK_16, bitDepth); decSampleHbdOffsetY += BLK_16 * strideComp[compCtr]; } /* end of component loop */ } } } delete grainStripe; return FGS_SUCCESS; } uint32_t SEIFilmGrainSynthesizer::fgsSimulationBlending_32x32(fgsProcessArgs *inArgs) { uint8_t numComp, compCtr; /* number of color components */ uint8_t log2ScaleFactor, h, v; uint8_t bitDepth; /*grain bit depth and decoded bit depth are assumed to be same */ uint32_t widthComp[MAX_NUM_COMPONENT], heightComp[MAX_NUM_COMPONENT], strideComp[MAX_NUM_COMPONENT]; Pel * decSampleBlk32, *decSampleOffsetY; Pel * decComp[MAX_NUM_COMPONENT]; int16_t scaleFactor; uint32_t kOffset, lOffset, grainStripeOffset; Pel * grainStripe; uint32_t x, y; uint32_t blockAvg, intensityInt; /* ec : seed to be used for the psudo random generator for a given color component */ uint32_t grainStripeWidth; uint32_t wdPadded; bitDepth = inArgs->bitDepth; numComp = inArgs->numComp; log2ScaleFactor = inArgs->pFgcParameters->m_log2ScaleFactor; for (compCtr = 0; compCtr < numComp; compCtr++) { decComp[compCtr] = inArgs->decComp[compCtr]; strideComp[compCtr] = inArgs->strideComp[compCtr]; heightComp[compCtr] = inArgs->heightComp[compCtr]; widthComp[compCtr] = inArgs->widthComp[compCtr]; } wdPadded = ((inArgs->widthComp[0] - 1) | 0x1F) + 1; grainStripe = new Pel[wdPadded * BLK_32]; if (0 == inArgs->pFgcParameters->m_filmGrainCharacteristicsCancelFlag) { for (compCtr = 0; compCtr < numComp; compCtr++) { if (1 == inArgs->pFgcParameters->m_compModel[compCtr].presentFlag) { uint32_t *offset_tmp = inArgs->fgsOffsets[compCtr]; decSampleOffsetY = decComp[compCtr]; grainStripeWidth = ((widthComp[compCtr] - 1) | 0x1F) + 1; // Make next muliptle of 32 /* Loop of 32x32 blocks */ for (y = 0; y < heightComp[compCtr]; y += BLK_32) { /* Initialization of grain stripe of 32xwidth size */ memset(grainStripe, 0, (grainStripeWidth * BLK_32 * sizeof(Pel))); for (x = 0; x < widthComp[compCtr]; x += BLK_32) { /* start position offset of decoded sample in x direction */ grainStripeOffset = x; decSampleBlk32 = decSampleOffsetY + x; blockAvg = blockAverage_32x32(decSampleBlk32, strideComp[compCtr], bitDepth); /* Selection of the component model */ intensityInt = inArgs->pGrainSynt->intensityInterval[compCtr][blockAvg]; if (INTENSITY_INTERVAL_MATCH_FAIL != intensityInt) { kOffset = (MSB16(*offset_tmp) % 36); kOffset &= 0xFFFC; lOffset = (LSB16(*offset_tmp) % 40); lOffset &= 0xFFF8; scaleFactor = 1 - 2 * BIT0(*offset_tmp); scaleFactor *= inArgs->pFgcParameters->m_compModel[compCtr].intensityValues[intensityInt].compModelValue[0]; h = inArgs->pFgcParameters->m_compModel[compCtr].intensityValues[intensityInt].compModelValue[1] - 2; v = inArgs->pFgcParameters->m_compModel[compCtr].intensityValues[intensityInt].compModelValue[2] - 2; /* 32x32 block grain simulation */ simulateGrainBlk32x32(grainStripe, grainStripeOffset, inArgs->pGrainSynt, grainStripeWidth, log2ScaleFactor, scaleFactor, kOffset, lOffset, h, v); } /* only if average falls in any interval */ /* uppdate the PRNG once per 16x16 block of samples */ offset_tmp++; } /* End of 32xwidth grain simulation */ /* deblocking at the vertical edges of 8x8 at 16xwidth*/ deblockGrainStripe(grainStripe, widthComp[compCtr], BLK_32, grainStripeWidth, BLK_32); blendStripe_32x32(decSampleOffsetY, grainStripe, widthComp[compCtr], strideComp[compCtr], grainStripeWidth, BLK_32, bitDepth); decSampleOffsetY += BLK_32 * strideComp[compCtr]; } /* end of component loop */ } } } delete grainStripe; return FGS_SUCCESS; }
/**************************************************************************** ** MIT License ** ** Copyright (C) 2020-2021 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com ** Author: Giuseppe D'Angelo <giuseppe.dangelo@kdab.com> ** ** This file is part of KDToolBox (https://github.com/KDAB/KDToolBox). ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** copies of the Software, ** and to permit persons to whom the Software is ** furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice (including the next paragraph) ** shall be included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF ** CONTRACT, TORT OR OTHERWISE, ** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ** DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <QApplication> #include <QPushButton> #include <QDebug> #include <messagehandler.h> int main(int argc, char **argv) { qSetMessagePattern(QStringLiteral("[%{if-debug}DBUG%{endif}%{if-info}INFO%{endif}%{if-warning}WARN%{endif}%{if-critical}CRIT%{endif}%{if-fatal}FATL%{endif}] %{message}")); QApplication app(argc, argv); qWarning() << "This is a warning message; no message handler has been registered yet."; qDebug() << "This is a debug message. We're now installing a handler for all warnings"; KDToolBox::handleMessage(QtWarningMsg, [](){ qDebug() << "***!!!*** 1st warning handler here: a warning happened"; }); qWarning() << "This is warning again. Before this warning, you should've had an extra print."; qDebug() << "This is a debug message; this did not trigger the handler because it's a debug, not a warning message."; qDebug() << "Now installing a handler that reacts only on warnings that begin with 'PANIC'."; KDToolBox::handleMessage(QtWarningMsg, QRegularExpression(QStringLiteral("^PANIC")), [](){ qDebug() << "***!!!*** 2nd warning handler here: a warning that begins with PANIC has been received"; }); qWarning() << "PANIC! Both warning handlers should've fired before this message"; qWarning() << "Another warning, this time only the first warning handler should've fired"; qCritical() << "Critical message. Handled also by a warning handler."; QPushButton button(QStringLiteral("Click to quit")); button.resize(500, 500); button.show(); QObject::connect(&button, &QPushButton::clicked, &app, &QApplication::quit); return app.exec(); }
// // Basic class to handle reading of static data // // Author: Alex V. Boreskoff // #include <stdio.h> #ifdef _WIN32 #include <fcntl.h> #include <io.h> #include <sys/stat.h> #else #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #define O_BINARY 0 #endif #ifdef MACOSX #include <stdlib.h> #else #include <malloc.h> #endif #include <memory.h> #include <string.h> #include "Data.h" Data :: Data ( void * ptr, int len ) { bits = (byte *) ptr; length = len; pos = 0; } Data :: Data ( const char * fileName ) { // make a fix for windows to replace '/' in file path // to windoze style '\\' if under windoze char * name = strdup ( fileName ); #ifdef _WIN32 char * ptr; while ( ( ptr = strchr ( name, '/' ) ) != NULL ) *ptr = '\\'; #endif bits = NULL; length = 0; pos = 0; file = name; int fd = open ( name, O_RDONLY | O_BINARY ); free ( name ); if ( fd == -1 ) return; #ifndef _WIN32 struct stat statBuf; fstat ( fd, &statBuf ); long len = statBuf.st_size; #else long len = filelength ( fd ); #endif if ( len == -1 ) { close ( fd ); return; } bits = (byte *) malloc ( len ); if ( bits == NULL ) { close ( fd ); return; } length = read ( fd, bits, len ); close ( fd ); } bool Data :: isOk () const { return bits != NULL; } void * Data :: getPtr ( int offs ) const { if ( offs < 0 || offs >= length ) return NULL; return bits + offs; } int Data :: getBytes ( void * ptr, int len ) { if ( pos >= length ) return -1; if ( pos + len > length ) len = length - pos; memcpy ( ptr, bits + pos, len ); pos += len; return len; } bool Data :: getString ( string& str, char term ) { if ( pos >= length ) return false; str = ""; while ( pos < length && bits [pos] != term ) str += bits [pos++]; if ( pos < length && bits [pos] == term ) pos ++; // skin OA part of line terminator (0D,0A) if ( term == '\r' && pos + 1 < length && bits [pos+1] == '\n' ) pos++; return true; } bool Data :: saveToFile ( const char * name ) const { int fd = open ( name, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, S_IWRITE ); if ( fd == -1 ) return false; write ( fd, bits, length ); close ( fd ); return true; }
// // Created by edward on 13.11.2019. // #include <fstream> #include <gtest/gtest.h> #include <stack> #include <toolbox/data.hpp> #include <toolbox/data/literals.h> #include <toolbox/data/transformers.h> using namespace toolbox::data; using namespace toolbox::data::literals; TEST(BytesData, Write) { bytes_data d1; d1.write(0, (uint8_t) 0x05); ASSERT_EQ(1, d1.size()); ASSERT_EQ(0x05, d1.at(0)); d1.write(1, (uint16_t) 0x0101); ASSERT_EQ(3, d1.size()); ASSERT_EQ((uint8_t) 0x01, d1.at(1)); ASSERT_EQ((uint8_t) 0x01, d1.at(2)); d1.write(3, (uint32_t) 20); ASSERT_EQ(3 + 4, d1.size()); ASSERT_EQ(20u >> 24u, d1.at(3)); ASSERT_EQ(20u >> 16u, d1.at(4)); ASSERT_EQ(20u >> 8u, d1.at(5)); ASSERT_EQ(20u & 0xFFu, d1.at(6)); d1.write(7, (uint64_t) 40ULL); ASSERT_EQ(3 + 4 + 8, d1.size()); ASSERT_EQ(40ULL >> 56u, d1.at(7)); ASSERT_EQ(40ULL >> 48u, d1.at(8)); ASSERT_EQ(40ULL >> 40u, d1.at(9)); ASSERT_EQ(40ULL >> 32u, d1.at(10)); ASSERT_EQ(40ULL >> 24u, d1.at(11)); ASSERT_EQ(40ULL >> 16u, d1.at(12)); ASSERT_EQ(40ULL >> 8u, d1.at(13)); ASSERT_EQ(40ULL & 0xFFu, d1.at(14)); size_t n = d1.size(); std::vector<uint8_t> tmp1 = {0x00, 0x01, 0x02, 0x03}; d1.write(n, tmp1); ASSERT_EQ(n + tmp1.size(), d1.size()); ASSERT_EQ(0x00u, d1.at(15)); ASSERT_EQ(0x01u, d1.at(16)); ASSERT_EQ(0x02u, d1.at(17)); ASSERT_EQ(0x03u, d1.at(18)); // 19 items now // size_t s2 = n + tmp1.size(); std::vector<uint8_t> tmp2(64); std::for_each(tmp2.begin(), tmp2.end(), [](uint8_t& v) { v = 0xFFu; }); ASSERT_EQ(64, tmp2.size()); // ok, let write 64 byte vector into the 9th d index d1.write(10, tmp2); ASSERT_EQ(74, d1.size()); ASSERT_EQ(0xFFu, d1.at(10)); ASSERT_EQ(0xFFu, d1.at(73)); // now replace making new tail with new data starting at position=10 d1.write_tail(10, tmp2); ASSERT_EQ(74, d1.size()); ASSERT_EQ(0xFFu, d1.at(10)); ASSERT_EQ(0xFFu, d1.at(73)); // now we've removed old tail with new // scheme: // [ 0 - 18 old data ] // we're inserted into the 10 index 64 bytes, and now we have // [ 0 - 9 old data, 10 - 73 new 64 bytes data ] // and size of BytesData was changed to 74 uint8_t t2[4] = {1, 2, 3, 4}; d1.push_back(t2, 4); ASSERT_EQ(78, d1.size()); ASSERT_EQ(1, d1.at(74)); ASSERT_EQ(2, d1.at(75)); ASSERT_EQ(3, d1.at(76)); ASSERT_EQ(4, d1.at(77)); d1.write(74, t2, 4); // if we're inserting out of bounds, than buffer resizes ASSERT_EQ(78, d1.size()); ASSERT_EQ(1, d1.at(74)); ASSERT_EQ(2, d1.at(75)); ASSERT_EQ(3, d1.at(76)); ASSERT_EQ(4, d1.at(77)); const bytes_data d2 = d1; d1.clear(); d1.resize(0); d1.write(0, d2); ASSERT_EQ(d1.size(), d2.size()); for (size_t i = 0; i < d1.size(); i++) { ASSERT_EQ(d1.at(i), d2.at(i)); } d1.clear(); d1.resize(0); // write over size, container automatically resize backend to new size d1.write(150, t2, 4); bytes_data d3 = d1; d1.clear(); d1.resize(0); d1.write(0, d3); ASSERT_EQ(d1.size(), d3.size()); for (size_t i = 0; i < d1.size(); i++) { ASSERT_EQ(d1.at(i), d3.at(i)); } bytes_data d4 = d1; d1.clear(); d1.resize(0); d1.write(0, std::move(d3)); ASSERT_EQ(d1.size(), d3.size()); for (size_t i = 0; i < d1.size(); i++) { ASSERT_EQ(d1.at(i), d3.at(i)); } } TEST(BytesData, Resize) { bytes_data d(32); for (int i = 0; i < 32; i++) { if (i < 16) { d.write(i, (uint8_t) 0x7F); } else { d.write(i, (uint8_t) 0xFF); } } bytes_data target(d.take_range_from(d.size() / 2)); ASSERT_EQ(16, target.size()); d.resize(16); ASSERT_EQ(16, d.size()); ASSERT_EQ((uint8_t) 0xFF, target.at(0)); ASSERT_EQ((uint8_t) 0xFF, target.at(15)); ASSERT_EQ((uint8_t) 0x7F, d.at(0)); ASSERT_EQ((uint8_t) 0x7F, d.at(15)); } TEST(BytesData, PopBackTo) { bytes_buffer d(32); for (int i = 0; i < 32; i++) { if (i < 16) { d.write(i, (uint8_t) 0x7F); } else { d.write(i, (uint8_t) 0xFF); } } bytes_data target(16); d.pop_back_to(target); ASSERT_EQ(16, target.size()); ASSERT_EQ(16, d.size()); ASSERT_EQ((uint8_t) 0xFF, target.at(0)); ASSERT_EQ((uint8_t) 0xFF, target.at(15)); ASSERT_EQ((uint8_t) 0x7F, d.at(0)); ASSERT_EQ((uint8_t) 0x7F, d.at(15)); bytes_data target2(8); d.pop_back_to(8, target2); ASSERT_EQ(8, target2.size()); ASSERT_EQ(8, d.size()); bytes_data target3(16); d.pop_back_to(target3); ASSERT_EQ(0, d.size()); ASSERT_EQ(16, target3.size()); ASSERT_EQ((uint8_t) 0x7F, target3.at(0)); ASSERT_EQ((uint8_t) 0x7F, target3.at(7)); ASSERT_EQ((uint8_t) 0x00, target3.at(15)); } TEST(BytesData, InsertIterator) { bytes_data d; std::vector<uint8_t> data = {1, 2, 3, 4}; size_t n = 0; n = d.write(d.begin(), data.begin(), data.end()); ASSERT_EQ(4, d.size()); ASSERT_EQ(4, n); std::vector<uint8_t> data2 = {5, 6, 7, 8}; n = d.write(2, data2.begin(), data2.end()); ASSERT_EQ(6, d.size()); ASSERT_EQ(4, n); d.clear(); d.resize(32); std::fill(d.begin(), d.end(), (uint8_t) 0x80); n = d.write(4, data2.begin(), data2.end()); ASSERT_EQ(4, n); ASSERT_EQ(32, d.size()); } TEST(BytesData, PushBackIterators) { bytes_data d; std::vector<uint8_t> src = {5, 6, 7, 8}; d.clear(); d.resize(0); d.push_back(src.begin(), src.end()); ASSERT_EQ(4, d.size()); ASSERT_EQ(5, d.at(0)); ASSERT_EQ(6, d.at(1)); ASSERT_EQ(7, d.at(2)); ASSERT_EQ(8, d.at(3)); const auto data3 = src; d.clear(); d.resize(0); d.push_back(data3.begin(), data3.end()); ASSERT_EQ(4, d.size()); ASSERT_EQ(5, d.at(0)); ASSERT_EQ(6, d.at(1)); ASSERT_EQ(7, d.at(2)); ASSERT_EQ(8, d.at(3)); bytes_data nd; nd.push_back(d); ASSERT_EQ(d.size(), nd.size()); ASSERT_EQ(d, nd); ASSERT_TRUE(d == nd); const bytes_data another("aaff"); d.clear(); d.resize(0); d.push_back(another); ASSERT_EQ(2, d.size()); ASSERT_EQ(0xAA, d.at(0)); ASSERT_EQ(0xFF, d.at(1)); const bytes_data another_move("aaff"); d.clear(); d.resize(0); d.push_back(std::move(another)); ASSERT_EQ(2, d.size()); ASSERT_EQ(0xAA, d.at(0)); ASSERT_EQ(0xFF, d.at(1)); } TEST(BytesData, WriteBatch) { bytes_data d; std::map<size_t, uint8_t> empty_data; d.write_batch(std::move(empty_data)); ASSERT_EQ(0, d.size()); } TEST(BytesData, Ranges) { bytes_data d; std::vector<uint8_t> tmp = {1, 2, 3, 4}; d.push_back(tmp); ASSERT_EQ(1, d.at(0)); ASSERT_EQ(2, d.at(1)); ASSERT_EQ(3, d.at(2)); ASSERT_EQ(4, d.at(3)); auto slice1 = d.take_first(2); ASSERT_EQ(2, slice1.size()); ASSERT_EQ(1, slice1.at(0)); ASSERT_EQ(2, slice1.at(1)); auto slice2 = d.take_last(2); ASSERT_EQ(2, slice2.size()); ASSERT_EQ(3, slice2.at(0)); ASSERT_EQ(4, slice2.at(1)); auto slice3 = d.take_range(0, 2); ASSERT_EQ(2, slice3.size()); ASSERT_EQ(1, slice3.at(0)); ASSERT_EQ(2, slice3.at(1)); auto slice4 = d.take_range(3, 4); ASSERT_EQ(1, slice4.size()); ASSERT_EQ(4, slice4.at(0)); auto slice5 = d.take_range(2, 4); ASSERT_EQ(2, slice5.size()); ASSERT_EQ(3, slice5.at(0)); ASSERT_EQ(4, slice5.at(1)); auto slice6 = d.take_range(4, 4); ASSERT_EQ(0, slice6.size()); bool s7threw = false; try { auto slice7 = d.take_range(5, 4); ASSERT_EQ(0, slice7.size()); } catch (const std::out_of_range& e) { s7threw = true; } ASSERT_TRUE(s7threw); bool s8threw = false; try { auto slice8 = d.take_range(5, 5); ASSERT_EQ(0, slice8.size()); } catch (const std::out_of_range& e) { s8threw = true; } ASSERT_TRUE(s8threw); bool s9threw = false; try { auto slice9 = d.take_range(0, 10); ASSERT_EQ(0, slice9.size()); } catch (const std::out_of_range& e) { s9threw = true; } ASSERT_TRUE(s9threw); bool s10threw = false; try { auto slice10 = d.take_range(500, 0); ASSERT_EQ(0, slice10.size()); } catch (const std::out_of_range& e) { s10threw = true; } ASSERT_TRUE(s10threw); } TEST(BytesData, push_back) { bytes_data d1; d1.push_back((uint8_t) 0x05); ASSERT_EQ(1, d1.size()); d1.push_back((uint16_t) 0x0101); ASSERT_EQ(3, d1.size()); d1.push_back((uint32_t) 0x20); ASSERT_EQ(3 + 4, d1.size()); d1.push_back((uint64_t) 0x40ULL); ASSERT_EQ(3 + 4 + 8, d1.size()); size_t n = d1.size(); std::vector<uint8_t> tmp1 = {0x0, 0x01, 0x02, 0x03}; d1.push_back(tmp1); ASSERT_EQ(n + tmp1.size(), d1.size()); } TEST(Buffer, PopFrontTo) { bytes_buffer buffer(256); ASSERT_EQ(256, buffer.size()); std::fill(buffer.begin(), buffer.end(), 0xFFu); bytes_buffer exData(74); std::fill(exData.begin(), exData.begin() + 10, 0x80u); ASSERT_EQ(0x80u, exData.at(0)); ASSERT_EQ(0x80u, exData.at(9)); ASSERT_EQ(0x0u, exData.at(exData.size() - 1)); size_t seq = 1; size_t rlen = 64; size_t left = 256; size_t written = 0; while (!buffer.empty()) { // stack write // getting from first // writing to end written += buffer.pop_front_to(rlen, exData.begin() + 10, exData); left -= rlen; ASSERT_EQ(left, buffer.size()); ASSERT_EQ(74, exData.size()); seq++; } ASSERT_EQ(256, written); ASSERT_EQ(0, buffer.size()); ASSERT_EQ(74, exData.size()); } TEST(Buffer, PopFrontLimit) { bytes_data chunk(64); std::fill(chunk.begin(), chunk.end(), (uint8_t) 0x80); bytes_buffer buffer(256); std::fill(buffer.begin(), buffer.end(), (uint8_t) 0xFF); uint16_t seq = 0; ASSERT_EQ(64, chunk.size()); ASSERT_EQ(256, buffer.size()); size_t left = 256; while (!buffer.empty()) { chunk.write(3, seq); size_t n = buffer.pop_front_to(5, chunk); std::cout << "Written to chunk: " << n << std::endl; std::cout << "Size of chunk: " << chunk.size() << std::endl; left -= n; ASSERT_EQ(left, buffer.size()); ASSERT_EQ(64, chunk.size()); seq++; } } TEST(BytesData, RealCase1) { bytes_data buffer(64); // 01 01 05 00 00 00 05 00 01 00 90 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 // 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 buffer.write(0, (uint8_t) 0x01); buffer.write(1, (uint8_t) 0x01); buffer.write(2, (uint8_t) 0x05); buffer.write(3, (uint8_t) 0x00); buffer.write(4, (uint8_t) 0x00); buffer.write(5, (uint8_t) 0x00); buffer.write(6, (uint8_t) 0x05); buffer.write(7, (uint8_t) 0x00); buffer.write(8, (uint8_t) 0x01); buffer.write(9, (uint8_t) 0x00); buffer.write(10, (uint8_t) 0x90); buffer.write(11, (uint8_t) 0x00); for (int i = 12; i < 64; i++) { buffer.write(i, (uint8_t) 0x0); } // parse header 5 bytes // 2 bytes auto channelId = buffer.to_num<uint16_t>(0); // 1 byte uint8_t commandTag = buffer.at(2); // 2 bytes auto cseq = buffer.to_num<uint16_t>(3); ASSERT_EQ((uint16_t) 0x0101, channelId); ASSERT_EQ((uint16_t) 0x05, commandTag); ASSERT_EQ(0x00, cseq); // data len ASSERT_EQ((uint16_t) 0x05, buffer.at(6)); // version ASSERT_EQ(0x00, buffer.at(7)); ASSERT_EQ((uint16_t) 0x01, buffer.at(8)); ASSERT_EQ(0x00, buffer.at(9)); uint16_t statusCode = buffer.to_num<uint16_t>(10); ASSERT_EQ((uint16_t) 0x9000, statusCode); } TEST(BytesData, WriteReadNumber) { bytes_data d(32); d.write(0, (uint16_t) 0x8080u); uint8_t buf[4] = {0xFFu, 0xFFu, 0xFFu, 0xFFu}; uint32_t num = (((uint32_t) buf[0]) << 24u) | (((uint32_t) buf[1]) << 16u) | (((uint32_t) buf[2]) << 8u) | (((uint32_t) buf[3])); ASSERT_EQ(UINT32_MAX, num); ASSERT_EQ(32, d.size()); ASSERT_EQ((uint16_t) 0x8080u, d.to_num<uint16_t>(0)); d.write(2, (uint32_t) UINT32_MAX); ASSERT_EQ(0xFFFFFFFFU, UINT32_MAX); ASSERT_EQ(32, d.size()); ASSERT_EQ(0xFFu, d.at(2)); ASSERT_EQ(0xFFu, d.at(3)); ASSERT_EQ(0xFFu, d.at(4)); ASSERT_EQ(0xFFu, d.at(5)); ASSERT_EQ(0xFFFFFFFFU, d.to_num<uint32_t>(2)); d.write(6, (uint64_t) UINT64_MAX); ASSERT_EQ(32, d.size()); ASSERT_EQ(0xFFu, d.at(6)); ASSERT_EQ(0xFFu, d.at(7)); ASSERT_EQ(0xFFu, d.at(8)); ASSERT_EQ(0xFFu, d.at(9)); ASSERT_EQ(0xFFu, d.at(10)); ASSERT_EQ(0xFFu, d.at(11)); ASSERT_EQ(0xFFu, d.at(12)); ASSERT_EQ(0xFFu, d.at(13)); ASSERT_EQ((uint64_t) UINT64_MAX, d.to_num<uint64_t>(6)); d.write(14, (uint8_t) 0xFFu); ASSERT_EQ(32, d.size()); ASSERT_EQ((uint8_t) 0xFFu, d.to_num<uint8_t>(14)); d.clear(); d.resize(2); d.write(0, (uint16_t) 257); ASSERT_EQ(2, d.size()); ASSERT_EQ((uint16_t) 257, d.to_num<uint16_t>()); } TEST(BytesData, ToNumAny) { bytes_data d; d.write(0, UINT64_MAX); uint64_t r1 = d.to_num_any(0, sizeof(uint64_t)); ASSERT_EQ(UINT64_MAX, r1); d.clear(); d.write(0, (uint8_t) 0xFF); auto r2 = d.to_num_any_size<uint8_t>(0, 0 + 1); ASSERT_EQ((uint8_t) 0xFF, r2); d.clear(); d.write(0, 250); auto r3 = d.to_num_any_size<uint32_t>(0); ASSERT_EQ((uint8_t) 250, r3); d.clear(); d.write(0, (uint32_t) UINT16_MAX); auto r5 = d.to_num_any_size<uint16_t>(0, 0 + sizeof(uint32_t)); ASSERT_EQ(UINT16_MAX, r5); d.clear(); d.write(0, (uint32_t) UINT16_MAX); auto r6 = d.to_num_any_size<uint32_t, uint16_t>(0); ASSERT_EQ(UINT16_MAX, r6); d.clear(); d.write(0, (uint8_t) 250); auto r4 = d.to_num_any_size<uint32_t>(0); ASSERT_NE((uint32_t) 250, r4); // r4 case works, only if data container has only 1 byte size, but there already 8, // so, if we would try to convert 0-4 indexes to uint32_t, we'll get little-endian encoding, toolbox does not // support little endian. If you need to convert between values, set 2 types explicitly, like below auto r7 = d.to_num_any_size<uint8_t, uint32_t>(0); ASSERT_EQ((uint32_t) 250, r7); auto r8 = d.to_num_any(0, 8); // the same issue, use explicit types ASSERT_NE(250ull, r8); d.clear(); d.resize(0); d.write_back((uint8_t) 0xFF); d.write_back((uint8_t) 0xFF); uint64_t val = d.to_num_any(0, 2); ASSERT_EQ(2, d.size()); ASSERT_EQ(0xFFFF, val); uint64_t val_no_bounds = d.to_num_any(); ASSERT_EQ(0xFFFF, val_no_bounds); } TEST(BytesData, CopyCtor) { std::stack<bytes_data> merge; bytes_data d1; d1.write_back((uint8_t) 1); d1.write_back((uint8_t) 2); d1.write_back((uint8_t) 3); merge.push(d1); std::cout << "Size of stack:" << merge.size() << "\n"; std::cout << "Top of stack: " << merge.top().size() << "\n"; const bytes_data a("ff00ff00"); bytes_data b(a); ASSERT_EQ(4, a.size()); ASSERT_EQ(4, b.size()); ASSERT_EQ(a, b); ASSERT_TRUE(a == b); } TEST(BytesData, Map) { bytes_data d = {(uint8_t) 0x01, (uint8_t) 0x02, (uint8_t) 0x01, (uint8_t) 0x02}; ASSERT_EQ(4, d.size()); ASSERT_EQ((uint8_t) 0x01, d.at(0)); ASSERT_EQ((uint8_t) 0x02, d.at(d.size() - 1)); d.map([](uint8_t val) { return (uint8_t)(val * 2); }); ASSERT_EQ(4, d.size()); ASSERT_EQ((uint8_t) 0x02, d.at(0)); ASSERT_EQ((uint8_t) 0x04, d.at(d.size() - 1)); } static std::vector<uint8_t> switch_01(std::vector<uint8_t> source) { return source; } static std::vector<uint8_t> switch_02(const std::vector<uint8_t>& source) { return source; } inline std::vector<uint8_t> switch_03(const std::vector<uint8_t>& source) { return source; } std::vector<uint8_t> switch_04(const std::vector<uint8_t>& source) { return source; } namespace example { namespace utils { std::vector<uint8_t> switch_05(const std::vector<uint8_t>& source) { return source; } } // namespace utils } // namespace example TEST(BytesData, SwitchMapFuncVar) { bytes_data d = {(uint8_t) 0x01, (uint8_t) 0x02, (uint8_t) 0x01, (uint8_t) 0x02}; d.switch_map(&switch_01); d.switch_map(switch_01); d.switch_map(&switch_02); d.switch_map(switch_02); d.switch_map(switch_03); d.switch_map(switch_04); d.switch_map(example::utils::switch_05); ASSERT_EQ(4, d.size()); ASSERT_EQ((uint8_t) 0x01, d.at(0)); ASSERT_EQ((uint8_t) 0x02, d.at(3)); } TEST(BytesData, SwitchMap) { bytes_data d = {(uint8_t) 0x01, (uint8_t) 0x02, (uint8_t) 0x01, (uint8_t) 0x02}; ASSERT_EQ(4, d.size()); ASSERT_EQ((uint8_t) 0x01, d.at(0)); ASSERT_EQ((uint8_t) 0x02, d.at(d.size() - 1)); d.switch_map([](std::vector<uint8_t> old) { std::vector<uint8_t> out; out.resize(old.size()); std::transform(old.begin(), old.end(), out.begin(), [](uint8_t val) { return val * 4; }); return out; }); ASSERT_EQ(4, d.size()); ASSERT_EQ((uint8_t) 0x04, d.at(0)); ASSERT_EQ((uint8_t) 0x08, d.at(d.size() - 1)); } TEST(BytesData, SwitchMapReduce) { bytes_data d = {(uint8_t) 0x01, (uint8_t) 0x02, (uint8_t) 0x01, (uint8_t) 0x02}; ASSERT_EQ(4, d.size()); ASSERT_EQ((uint8_t) 0x01, d.at(0)); ASSERT_EQ((uint8_t) 0x02, d.at(d.size() - 1)); d.switch_map([](std::vector<uint8_t> old) { std::vector<uint8_t> out; out.resize(old.size() - 2); std::transform(old.begin(), old.begin() + 2, out.begin(), [](uint8_t val) { return val * 4; }); return out; }); ASSERT_EQ(2, d.size()); ASSERT_EQ((uint8_t) 0x04, d.at(0)); ASSERT_EQ((uint8_t) 0x08, d.at(d.size() - 1)); } TEST(BytesData, SwitchMapCopy) { bytes_data d = {(uint8_t) 0x01, (uint8_t) 0x02, (uint8_t) 0x01, (uint8_t) 0x02}; ASSERT_EQ(4, d.size()); ASSERT_EQ((uint8_t) 0x01, d.at(0)); ASSERT_EQ((uint8_t) 0x02, d.at(3)); auto res = d.switch_map_c([](std::vector<uint8_t> old) { std::vector<uint8_t> out(old.size()); std::transform(old.begin(), old.end(), out.begin(), [](uint8_t val) { return (uint8_t)(val * 2); }); return out; }); ASSERT_EQ(4, res.size()); ASSERT_EQ((uint8_t) 0x02, res.at(0)); ASSERT_EQ((uint8_t) 0x04, res.at(1)); ASSERT_EQ((uint8_t) 0x02, res.at(2)); ASSERT_EQ((uint8_t) 0x04, res.at(3)); ASSERT_EQ(4, d.size()); ASSERT_EQ((uint8_t) 0x01, d.at(0)); ASSERT_EQ((uint8_t) 0x02, d.at(1)); ASSERT_EQ((uint8_t) 0x01, d.at(2)); ASSERT_EQ((uint8_t) 0x02, d.at(3)); } TEST(BytesData, MapToStrings) { bytes_data d = bytes_data::from_string_raw("hello map to"); auto string_d = d.map_to<char>([](uint8_t val) { return (char) val; }); ASSERT_EQ(d.size(), string_d.size()); std::string res = std::string(string_d.data(), string_d.data() + string_d.size()); ASSERT_STREQ("hello map to", res.c_str()); std::cout << res << std::endl; } TEST(BytesData, InitializerVectors) { bytes_data d = { {0x0, 0x0, 0x0, 'a'}, {0x1, 0x1, 0x1, 'b'}}; ASSERT_EQ(8, d.size()); ASSERT_EQ(0x0, d.at(0)); ASSERT_EQ(0x0, d.at(2)); ASSERT_EQ('a', d.at(3)); ASSERT_EQ(0x1, d.at(4)); ASSERT_EQ(0x1, d.at(6)); ASSERT_EQ('b', d.at(7)); } TEST(BytesData, Filter) { bytes_data d = {0x0, 0x0, 0x0, 0x1}; auto filter_no_zeroes = [](uint8_t v) { return v != 0x0; }; d.filter(filter_no_zeroes); ASSERT_EQ(1, d.size()); ASSERT_EQ(0x1, d.at(0)); bytes_data d2 = {0x1, 0x0, 0x1, 0x0}; bytes_data res = d2.filter_c(filter_no_zeroes); ASSERT_EQ(4, d2.size()); ASSERT_EQ(0x1, d2.at(0)); ASSERT_EQ(0x0, d2.at(1)); ASSERT_EQ(0x1, d2.at(2)); ASSERT_EQ(0x0, d2.at(3)); ASSERT_EQ(2, res.size()); ASSERT_EQ(0x1, res.at(0)); ASSERT_EQ(0x1, res.at(1)); } TEST(BytesData, Base64Transform) { std::string target = "aGVsbG8gd29ybGQ="; std::string source = "hello world"; bytes_data d = bytes_data::from_string_raw(source); d.switch_map(to_base_64); ASSERT_EQ(target.size(), d.size()); ASSERT_STREQ(target.c_str(), d.to_string().c_str()); d.switch_map(from_base_64); ASSERT_EQ(source.size(), d.size()); ASSERT_STREQ(source.c_str(), d.to_string().c_str()); } TEST(BytesData, OutputStream) { bytes_data data = bytes_data::from_string_raw("hello streams"); std::stringstream ss; ss << data; ASSERT_STREQ("hello streams", ss.str().c_str()); } TEST(BytesData, InputStream) { std::stringstream ss; ss << "abc"; bytes_data d; ss >> d; ASSERT_EQ(3, d.size()); ASSERT_EQ('a', d.at(0)); ASSERT_EQ('b', d.at(1)); ASSERT_EQ('c', d.at(2)); } TEST(BytesData, ConverterToString) { bytes_data data = bytes_data::from_string_raw("hello streams"); // this works only on c++17, as it have type deduction std::string result = data.convert(bytes_to_string()); } template<size_t N> struct conv_get_n { char operator()(const bytes_data& source) { return (char) source.at(N); } template<size_t N2> static char get(const bytes_data& source) { return (char) source.at(N2); } }; static char get_s(const bytes_data& source) { return source.at(0); } TEST(BytesData, CustomConverter) { bytes_data data = bytes_data::from_string_raw("hello streams"); char res = data.convert<char>(std::bind(conv_get_n<0>::get<0>, std::placeholders::_1)); char res2 = data.convert<char>(&conv_get_n<1>::get<1>); char res3 = data.convert<char>(conv_get_n<2>()); char res4 = data.convert<char>(get_s); ASSERT_EQ('h', res); ASSERT_EQ('e', res2); ASSERT_EQ('l', res3); ASSERT_EQ('h', res4); } TEST(BytesData, FromUint8PointerArray) { const uint8_t val[4] = {'a', 'b', 'c', 'd'}; bytes_data data(val, 4); ASSERT_EQ(4, data.size()); ASSERT_EQ('a', data.at(0)); ASSERT_EQ('b', data.at(1)); ASSERT_EQ('c', data.at(2)); ASSERT_EQ('d', data.at(3)); } TEST(BytesData, FromCharPointerArray) { const char val[4] = {'a', 'b', 'c', 'd'}; bytes_data data = bytes_data::from_chars(val, sizeof(val)); ASSERT_EQ(4, data.size()); ASSERT_EQ('a', data.at(0)); ASSERT_EQ('b', data.at(1)); ASSERT_EQ('c', data.at(2)); ASSERT_EQ('d', data.at(3)); } TEST(BytesData, FromCharVector) { const std::vector<char> val = {'a', 'b', 'c', 'd'}; bytes_data data = bytes_data::from_chars(val); ASSERT_EQ(4, data.size()); ASSERT_EQ('a', data.at(0)); ASSERT_EQ('b', data.at(1)); ASSERT_EQ('c', data.at(2)); ASSERT_EQ('d', data.at(3)); } TEST(BytesData, FromHexCString) { const char* hex = "aaaabbbbcccc"; bytes_data d(hex); ASSERT_EQ(6, d.size()); ASSERT_EQ(0xAA, d.at(0)); ASSERT_EQ(0xAA, d.at(1)); ASSERT_EQ(0xBB, d.at(2)); ASSERT_EQ(0xBB, d.at(3)); ASSERT_EQ(0xCC, d.at(4)); ASSERT_EQ(0xCC, d.at(5)); ASSERT_STREQ(hex, d.to_hex().c_str()); } TEST(BytesData, FromHexString) { const std::string hex = "aaaabbbbcccc"; bytes_data d(hex); ASSERT_EQ(6, d.size()); ASSERT_EQ(0xAA, d.at(0)); ASSERT_EQ(0xAA, d.at(1)); ASSERT_EQ(0xBB, d.at(2)); ASSERT_EQ(0xBB, d.at(3)); ASSERT_EQ(0xCC, d.at(4)); ASSERT_EQ(0xCC, d.at(5)); ASSERT_STREQ(hex.c_str(), d.to_hex().c_str()); } TEST(BytesData, WriteBackInt8) { bytes_data d; d.write_back((uint8_t) 100); ASSERT_EQ(1, d.size()); ASSERT_EQ((uint8_t) 100, d.at(0)); } TEST(BytesData, WriteBackInt16) { bytes_data d; d.write_back((uint16_t) 100); ASSERT_EQ(2, d.size()); ASSERT_EQ((uint8_t) 0, d.at(0)); ASSERT_EQ((uint8_t) 100, d.at(1)); } TEST(BytesData, WriteBackInt32) { bytes_data d; d.write_back((uint32_t) 100); ASSERT_EQ(4, d.size()); ASSERT_EQ((uint32_t) 100, d.to_num_any_size<uint32_t>(0, 4)); } TEST(BytesData, WriteBackInt64) { bytes_data d; d.write_back((uint64_t) 100); ASSERT_EQ(8, d.size()); ASSERT_EQ((uint32_t) 100, d.to_num_any_size<uint32_t>(0, 8)); } TEST(BytesData, PushBackSingleChar) { bytes_data d; d.push_back('w'); ASSERT_EQ(1, d.size()); ASSERT_EQ('w', d.at(0)); d.push_back('o'); ASSERT_EQ(2, d.size()); ASSERT_EQ('o', d.at(1)); } TEST(BytesData, PushBackInt16) { bytes_data d; d.push_back((uint16_t) 100); ASSERT_EQ(2, d.size()); ASSERT_EQ((uint8_t) 0, d.at(0)); ASSERT_EQ((uint8_t) 100, d.at(1)); } TEST(BytesData, PushBackInt32) { bytes_data d; d.push_back((uint32_t) 100); ASSERT_EQ(4, d.size()); ASSERT_EQ((uint32_t) 100, d.to_num_any_size<uint32_t>(0, 4)); } TEST(BytesData, PushBackInt64) { bytes_data d; d.push_back((uint64_t) 100); d.push_back((uint64_t) 200); ASSERT_EQ(16, d.size()); ASSERT_EQ((uint64_t) 100, d.to_num_any_size<uint32_t>(0, 8)); ASSERT_EQ((uint64_t) 200, d.to_num_any_size<uint32_t>(8, 16)); uint64_t any_val_a = d.to_num_any_size<uint64_t>(0); uint64_t any_val_b = d.to_num_any_size<uint64_t>(8); ASSERT_EQ((uint64_t) 100, any_val_a); ASSERT_EQ((uint64_t) 200, any_val_b); } /// \brief to_num_any - exception-less, if data is empty, it will return 0 TEST(BytesData, ToNumAnyOnEmpty) { bytes_data d; uint64_t val = d.to_num_any(0, 8); ASSERT_EQ(0, d.size()); ASSERT_EQ(0, val); } TEST(BytesData, ToNumOperators) { bytes_data d; d.write_back((uint8_t) 0xFF); ASSERT_EQ(1, d.size()); ASSERT_EQ((uint8_t) 0xFF, (uint8_t) d); d.clear(); d.resize(0); d.write_back((char) 'w'); ASSERT_EQ(1, d.size()); ASSERT_EQ('w', (char) d); d.clear(); d.resize(0); d.write_back((uint16_t) 0xFFFF); ASSERT_EQ(2, d.size()); ASSERT_EQ((uint16_t) 0xFFFF, (uint16_t) d); d.clear(); d.resize(0); d.write_back((uint32_t) 0xFFFFFFFF); ASSERT_EQ(4, d.size()); ASSERT_EQ((uint32_t) 0xFFFFFFFF, (uint32_t) d); d.clear(); d.resize(0); d.write_back((uint64_t) UINT64_MAX); ASSERT_EQ(8, d.size()); ASSERT_EQ((uint64_t) UINT64_MAX, (uint64_t) d); } TEST(BytesData, CopySwapCtor) { bytes_data target(65); bytes_data some_data; for (size_t i = 0; i < 65; i++) { some_data.write(i, (uint8_t) 0xFF); } ASSERT_NE(target, some_data); ASSERT_EQ(target.size(), some_data.size()); target = some_data; ASSERT_EQ(target, some_data); target = std::move(some_data); ASSERT_NE(target, some_data); } TEST(BytesArray, OutOfRangeError) { bytes_array<32> d; ASSERT_EQ(32, d.size()); bool t1 = false; try { d.write(64, 0xFF); } catch (const std::out_of_range& e) { t1 = true; } ASSERT_TRUE(t1); bool t2 = false; try { d.write(32, 0xFF); } catch (const std::out_of_range& e) { t2 = true; } ASSERT_TRUE(t2); bool t3 = false; try { d.write(31, 0xFF); } catch (const std::out_of_range& e) { t1 = true; } ASSERT_FALSE(t3); } TEST(BytesArray, Write) { bytes_array<10> d; std::vector<uint8_t> ex(12); std::fill(ex.begin(), ex.end(), (uint8_t) 0xFF); d.write(0, ex); ASSERT_EQ(10, d.size()); ASSERT_EQ(0xFF, d.at(0)); ASSERT_EQ(0xFF, d.at(d.size() - 1)); d.clear(); d.write(2, ex); ASSERT_EQ(10, d.size()); ASSERT_EQ(0, d.at(0)); ASSERT_EQ(0xFF, d.at(2)); ASSERT_EQ(0xFF, d.at(d.size() - 1)); d.clear(); bool t = false; try { d.write(20, ex); } catch (const std::out_of_range& e) { t = true; } ASSERT_TRUE(t); ASSERT_EQ(10, d.size()); ASSERT_EQ(0, d.at(0)); ASSERT_EQ(0, d.at(2)); ASSERT_EQ(0, d.at(d.size() - 1)); d = ex; ASSERT_EQ(10, d.size()); ASSERT_EQ(0xFF, d.at(0)); ASSERT_EQ(0xFF, d.at(d.size() - 1)); d.clear(); ex = std::vector<uint8_t>(8); std::fill(ex.begin(), ex.end(), (uint8_t) 0xFF); d = ex; ASSERT_EQ(10, d.size()); ASSERT_EQ(0xFF, d.at(0)); ASSERT_EQ(0xFF, d.at(7)); ASSERT_EQ(0x00, d.at(8)); ASSERT_EQ(0x00, d.at(d.size() - 1)); //uint8 d.clear(); t = false; try { d.write(10, (uint8_t) 10); } catch (const std::out_of_range& e) { t = true; } ASSERT_TRUE(t); //uint16 d.clear(); t = false; try { d.write(9, (uint16_t) 10); } catch (const std::out_of_range& e) { t = true; } ASSERT_TRUE(t); //uint32 d.clear(); t = false; try { d.write(8, (uint32_t) 10); } catch (const std::out_of_range& e) { t = true; } ASSERT_TRUE(t); //uint64 - ok d.clear(); t = false; try { d.write(2, (uint64_t) 10); } catch (const std::out_of_range& e) { t = true; } ASSERT_FALSE(t); //uint64 - ok d.clear(); t = false; try { d.write(0, (uint64_t) 10); } catch (const std::out_of_range& e) { t = true; } ASSERT_FALSE(t); //uint64 - fail d.clear(); t = false; try { d.write(3, (uint64_t) 10); } catch (const std::out_of_range& e) { t = true; } ASSERT_TRUE(t); //write basic_data - fail d.clear(); t = false; try { bytes_data tmp = ex; d.write(20, tmp); } catch (const std::out_of_range& e) { t = true; } ASSERT_TRUE(t); //write basic_data - ok d.clear(); t = false; try { // ex.size() = 8 bytes_data tmp = ex; d.write(2, tmp); } catch (const std::out_of_range& e) { t = true; } ASSERT_FALSE(t); //write basic_data - ok, silently strip data, write to position from input start d.clear(); t = false; try { // ex.size() = 8 bytes_data tmp = ex; d.write(3, tmp); } catch (const std::out_of_range& e) { t = true; } ASSERT_FALSE(t); ASSERT_EQ(0xFF, ex.at(3)); }
; A139716: If k is the largest divisor of n that is <= sqrt(n) then a(n) = n - k^2. ; 0,1,2,0,4,2,6,4,0,6,10,3,12,10,6,0,16,9,18,4,12,18,22,8,0,22,18,12,28,5,30,16,24,30,10,0,36,34,30,15,40,6,42,28,20,42,46,12,0,25,42,36,52,18,30,7,48,54,58,24,60,58,14,0,40,30,66,52,60,21,70,8,72,70,50,60,28,42 mov $1,$0 add $1,1 mov $2,$1 lpb $1 lpb $0 mov $0,$2 dif $0,$1 sub $0,$1 mul $0,$1 lpe sub $1,1 lpe
/** * @file * @brief Player related functions. **/ #include "AppHdr.h" #include "player.h" #include <algorithm> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> #include "ability.h" #include "abyss.h" #include "act-iter.h" #include "areas.h" #include "art-enum.h" #include "attack.h" #include "bloodspatter.h" #include "branch.h" #include "chardump.h" #include "cloud.h" #include "coordit.h" #include "delay.h" #include "dgn-overview.h" #include "dgn-event.h" #include "directn.h" #include "english.h" #include "env.h" #include "errors.h" #include "exercise.h" #include "files.h" #include "food.h" #include "god-abil.h" #include "god-conduct.h" #include "god-passive.h" #include "god-wrath.h" #include "hints.h" #include "hiscores.h" #include "invent.h" #include "item-prop.h" #include "items.h" #include "item-use.h" #include "kills.h" #include "level-state-type.h" #include "libutil.h" #include "macro.h" #include "melee-attack.h" #include "message.h" #include "mon-place.h" #include "mutation.h" #include "nearby-danger.h" #include "notes.h" #include "output.h" #include "player-equip.h" #include "player-save-info.h" #include "player-stats.h" #include "prompt.h" #include "religion.h" #include "shout.h" #include "skills.h" #include "species.h" // random_starting_species #include "spl-damage.h" #include "spl-selfench.h" #include "spl-transloc.h" #include "spl-util.h" #include "sprint.h" #include "stairs.h" #include "stash.h" #include "state.h" #include "status.h" #include "stepdown.h" #include "stringutil.h" #include "terrain.h" #ifdef USE_TILE #include "tilepick.h" #include "tileview.h" #endif #include "transform.h" #include "traps.h" #include "travel.h" #include "view.h" #include "wizard-option-type.h" #include "xom.h" static void _moveto_maybe_repel_stairs() { const dungeon_feature_type new_grid = env.grid(you.pos()); const command_type stair_dir = feat_stair_direction(new_grid); if (stair_dir == CMD_NO_CMD || new_grid == DNGN_ENTER_SHOP || !you.duration[DUR_REPEL_STAIRS_MOVE]) { return; } int pct = you.duration[DUR_REPEL_STAIRS_CLIMB] ? 29 : 50; // When the effect is still strong, the chance to actually catch // a stair is smaller. (Assuming the duration starts out at 1000.) const int dur = max(0, you.duration[DUR_REPEL_STAIRS_MOVE] - 700); pct += dur/10; if (x_chance_in_y(pct, 100)) { const string stair_str = feature_description_at(you.pos(), false, DESC_THE); const string prep = feat_preposition(new_grid, true, &you); if (slide_feature_over(you.pos())) { mprf("%s slides away as you move %s it!", stair_str.c_str(), prep.c_str()); if (player_in_a_dangerous_place() && one_chance_in(5)) xom_is_stimulated(25); } } } bool check_moveto_cloud(const coord_def& p, const string &move_verb, bool *prompted) { if (you.confused()) return true; const cloud_type ctype = env.map_knowledge(p).cloud(); // Don't prompt if already in a cloud of the same type. if (is_damaging_cloud(ctype, true, cloud_is_yours_at(p)) && ctype != cloud_type_at(you.pos()) && !crawl_state.disables[DIS_CONFIRMATIONS]) { // Don't prompt for steam unless we're at uncomfortably low hp. if (ctype == CLOUD_STEAM) { int threshold = 20; if (player_res_steam() < 0) threshold = threshold * 3 / 2; threshold = threshold * you.time_taken / BASELINE_DELAY; // Do prompt if we'd lose icemail, though. if (you.hp > threshold && !you.has_mutation(MUT_ICEMAIL)) return true; } // Don't prompt for meph if we have clarity, unless at very low HP. if (ctype == CLOUD_MEPHITIC && you.clarity(false) && you.hp > 2 * you.time_taken / BASELINE_DELAY) { return true; } if (prompted) *prompted = true; string prompt = make_stringf("Really %s into that cloud of %s?", move_verb.c_str(), cloud_type_name(ctype).c_str()); learned_something_new(HINT_CLOUD_WARNING); if (!yesno(prompt.c_str(), false, 'n')) { canned_msg(MSG_OK); return false; } } return true; } bool check_moveto_trap(const coord_def& p, const string &move_verb, bool *prompted) { // Boldly go into the unknown (for shadow step and other ranged move // prompts) if (env.map_knowledge(p).trap() == TRAP_UNASSIGNED) return true; // If there's no trap, let's go. trap_def* trap = trap_at(p); if (!trap) return true; if (trap->type == TRAP_ZOT && !trap->is_safe() && !crawl_state.disables[DIS_CONFIRMATIONS]) { string msg = "Do you really want to %s into the Zot trap?"; string prompt = make_stringf(msg.c_str(), move_verb.c_str()); if (prompted) *prompted = true; if (!yes_or_no("%s", prompt.c_str())) { canned_msg(MSG_OK); return false; } } else if (!trap->is_safe() && !crawl_state.disables[DIS_CONFIRMATIONS]) { string prompt; if (prompted) *prompted = true; prompt = make_stringf("Really %s %s that %s?", move_verb.c_str(), (trap->type == TRAP_ALARM || trap->type == TRAP_PLATE) ? "onto" : "into", feature_description_at(p, false, DESC_BASENAME).c_str()); if (!yesno(prompt.c_str(), true, 'n')) { canned_msg(MSG_OK); return false; } } return true; } static bool _check_moveto_dangerous(const coord_def& p, const string& msg) { if (you.can_swim() && feat_is_water(env.grid(p)) || you.airborne() || !is_feat_dangerous(env.grid(p))) { return true; } if (!msg.empty()) mpr(msg); else if (species_likes_water(you.species) && feat_is_water(env.grid(p))) mpr("You cannot enter water in your current form."); else canned_msg(MSG_UNTHINKING_ACT); return false; } bool check_moveto_terrain(const coord_def& p, const string &move_verb, const string &msg, bool *prompted) { // Boldly go into the unknown (for shadow step and other ranged move // prompts) if (!env.map_knowledge(p).known()) return true; if (!_check_moveto_dangerous(p, msg)) return false; if (!you.airborne() && env.grid(you.pos()) != DNGN_TOXIC_BOG && env.grid(p) == DNGN_TOXIC_BOG) { string prompt; if (prompted) *prompted = true; if (!msg.empty()) prompt = msg + " "; prompt += "Are you sure you want to " + move_verb + " into a toxic bog?"; if (!yesno(prompt.c_str(), false, 'n')) { canned_msg(MSG_OK); return false; } } if (!need_expiration_warning() && need_expiration_warning(p) && !crawl_state.disables[DIS_CONFIRMATIONS]) { string prompt; if (prompted) *prompted = true; if (!msg.empty()) prompt = msg + " "; prompt += "Are you sure you want to " + move_verb; if (you.ground_level()) prompt += " into "; else prompt += " over "; prompt += env.grid(p) == DNGN_DEEP_WATER ? "deep water" : "lava"; prompt += need_expiration_warning(DUR_FLIGHT, p) ? " while you are losing your buoyancy?" : " while your transformation is expiring?"; if (!yesno(prompt.c_str(), false, 'n')) { canned_msg(MSG_OK); return false; } } return true; } bool check_moveto_exclusions(const vector<coord_def> &areas, const string &move_verb, bool *prompted) { const bool you_pos_excluded = is_excluded(you.pos()) && !is_stair_exclusion(you.pos()); if (you_pos_excluded || crawl_state.disables[DIS_CONFIRMATIONS]) return true; int count = 0; for (auto p : areas) { if (is_excluded(p) && !is_stair_exclusion(p)) count++; } if (count == 0) return true; const string prompt = make_stringf((count == (int) areas.size() ? "Really %s into a travel-excluded area?" : "You might %s into a travel-excluded area, are you sure?"), move_verb.c_str()); if (prompted) *prompted = true; if (!yesno(prompt.c_str(), false, 'n')) { canned_msg(MSG_OK); return false; } return true; } bool check_moveto_exclusion(const coord_def& p, const string &move_verb, bool *prompted) { return check_moveto_exclusions({p}, move_verb, prompted); } bool check_moveto(const coord_def& p, const string &move_verb, const string &msg) { return check_moveto_terrain(p, move_verb, msg) && check_moveto_cloud(p, move_verb) && check_moveto_trap(p, move_verb) && check_moveto_exclusion(p, move_verb); } // Returns true if this is a valid swap for this monster. If true, then // the valid location is set in loc. (Otherwise loc becomes garbage.) bool swap_check(monster* mons, coord_def &loc, bool quiet) { loc = you.pos(); if (you.is_stationary()) return false; // Don't move onto dangerous terrain. if (is_feat_dangerous(grd(mons->pos()))) { canned_msg(MSG_UNTHINKING_ACT); return false; } if (mons_is_projectile(*mons)) { if (!quiet) mpr("It's unwise to walk into this."); return false; } if (mons->caught()) { if (!quiet) { simple_monster_message(*mons, make_stringf(" is %s!", held_status(mons)).c_str()); } return false; } if (mons->is_constricted()) { if (!quiet) simple_monster_message(*mons, " is being constricted!"); return false; } if (mons->is_stationary() || mons->asleep() || mons->cannot_move()) { if (!quiet) simple_monster_message(*mons, " cannot move out of your way!"); return false; } // prompt when swapping into known zot traps if (!quiet && trap_at(loc) && trap_at(loc)->type == TRAP_ZOT && !yes_or_no("Do you really want to swap %s into the Zot trap?", mons->name(DESC_YOUR).c_str())) { return false; } // First try: move monster onto your position. bool swap = !monster_at(loc) && monster_habitable_grid(mons, grd(loc)); if (monster_at(loc) && monster_at(loc)->type == MONS_TOADSTOOL && mons->type == MONS_WANDERING_MUSHROOM) { swap = monster_habitable_grid(mons, grd(loc)); } // Choose an appropriate habitat square at random around the target. if (!swap) { int num_found = 0; for (adjacent_iterator ai(mons->pos()); ai; ++ai) if (!monster_at(*ai) && monster_habitable_grid(mons, grd(*ai)) && one_chance_in(++num_found)) { loc = *ai; } if (num_found) swap = true; } if (!swap && !quiet) { // Might not be ideal, but it's better than insta-killing // the monster... maybe try for a short blink instead? - bwr simple_monster_message(*mons, " cannot make way for you."); // FIXME: activity_interrupt::hit_monster isn't ideal. interrupt_activity(activity_interrupt::hit_monster, mons); } return swap; } static void _splash() { if (you.can_swim()) noisy(4, you.pos(), "Floosh!"); else if (!you.can_water_walk()) noisy(8, you.pos(), "Splash!"); } void moveto_location_effects(dungeon_feature_type old_feat, bool stepped, const coord_def& old_pos) { const dungeon_feature_type new_grid = env.grid(you.pos()); // Terrain effects. if (is_feat_dangerous(new_grid)) fall_into_a_pool(new_grid); // called after fall_into_a_pool, in case of emergency untransform if (you.species == SP_MERFOLK) merfolk_check_swimming(stepped); if (you.ground_level()) { if (feat_is_water(new_grid)) { if (!stepped) _splash(); if (!you.can_swim() && !you.can_water_walk()) { if (!feat_is_water(old_feat)) { if (new_grid == DNGN_TOXIC_BOG) { mprf("You %s the toxic bog.", stepped ? "enter" : "fall into"); } else { mprf("You %s the %s water.", stepped ? "enter" : "fall into", new_grid == DNGN_SHALLOW_WATER ? "shallow" : "deep"); } } if (new_grid == DNGN_DEEP_WATER && old_feat != DNGN_DEEP_WATER) mpr("You sink to the bottom."); if (!feat_is_water(old_feat)) { mpr("Moving in this stuff is going to be slow."); if (you.invisible()) mpr("...and don't expect to remain undetected."); } } if (you.species == SP_OCTOPODE && !feat_is_water(old_feat) && you.invisible()) { mpr("Don't expect to remain undetected while in the water."); } } else if (you.props.exists(TEMP_WATERWALK_KEY)) you.props.erase(TEMP_WATERWALK_KEY); } id_floor_items(); // Falling into a toxic bog, take the damage if (old_pos == you.pos() && stepped) actor_apply_toxic_bog(&you); // Traps go off. // (But not when losing flight - i.e., moving into the same tile) trap_def* ptrap = trap_at(you.pos()); if (ptrap && old_pos != you.pos()) ptrap->trigger(you); if (stepped) _moveto_maybe_repel_stairs(); } // Use this function whenever the player enters (or lands and thus re-enters) // a grid. // // stepped - normal walking moves void move_player_to_grid(const coord_def& p, bool stepped) { ASSERT(!crawl_state.game_is_arena()); ASSERT_IN_BOUNDS(p); if (!stepped) tornado_move(p); // assuming that entering the same square means coming from above (flight) const coord_def old_pos = you.pos(); const bool from_above = (old_pos == p); const dungeon_feature_type old_grid = (from_above) ? DNGN_FLOOR : grd(old_pos); // Really must be clear. ASSERT(you.can_pass_through_feat(grd(p))); // Better not be an unsubmerged monster either. ASSERT(!monster_at(p) || monster_at(p)->submerged() || fedhas_passthrough(monster_at(p)) || mons_is_player_shadow(*monster_at(p))); // Move the player to new location. you.moveto(p, true); viewwindow(); moveto_location_effects(old_grid, stepped, old_pos); } /** * Check if the given terrain feature is safe for the player to move into. * (Or, at least, not instantly lethal.) * * @param grid The type of terrain feature under consideration. * @param permanently Whether to disregard temporary effects (non-permanent * flight, forms, etc) * @param ignore_flight Whether to ignore all forms of flight (including * permanent flight) * @return Whether the terrain is safe. */ bool is_feat_dangerous(dungeon_feature_type grid, bool permanently, bool ignore_flight) { if (!ignore_flight && (you.permanent_flight() || you.airborne() && !permanently)) { return false; } else if (grid == DNGN_DEEP_WATER && !player_likes_water(permanently) || grid == DNGN_LAVA) { return true; } else return false; } bool is_map_persistent() { return !testbits(your_branch().branch_flags, brflag::no_map) || env.properties.exists(FORCE_MAPPABLE_KEY); } bool player_in_hell(bool vestibule) { return vestibule ? is_hell_branch(you.where_are_you) : is_hell_subbranch(you.where_are_you); } /** * Is the player in the slightly-special version of the abyss that AKs start * in? */ bool player_in_starting_abyss() { return you.chapter == CHAPTER_POCKET_ABYSS && player_in_branch(BRANCH_ABYSS) && you.depth <= 1; } bool player_in_connected_branch() { return is_connected_branch(you.where_are_you); } bool player_likes_water(bool permanently) { return !permanently && you.can_water_walk() || (species_likes_water(you.species) || !permanently) && form_likes_water(); } /** * Is the player considered to be closely related, if not the same species, to * the given monster? (See mon-data.h for species/genus info.) * * @param mon The type of monster to be compared. * @return Whether the player's species is related to the one given. */ bool is_player_same_genus(const monster_type mon) { return mons_genus(mon) == mons_genus(player_mons(false)); } void update_player_symbol() { you.symbol = Options.show_player_species ? player_mons() : transform_mons(); } monster_type player_mons(bool transform) { monster_type mons; if (transform) { mons = transform_mons(); if (mons != MONS_PLAYER) return mons; } mons = player_species_to_mons_species(you.species); if (mons == MONS_ORC) { if (you_worship(GOD_BEOGH)) { mons = (you.piety >= piety_breakpoint(4)) ? MONS_ORC_HIGH_PRIEST : MONS_ORC_PRIEST; } } else if (mons == MONS_OGRE) { const skill_type sk = best_skill(SK_FIRST_SKILL, SK_LAST_SKILL); if (sk >= SK_SPELLCASTING && sk <= SK_LAST_MAGIC) mons = MONS_OGRE_MAGE; } return mons; } void update_vision_range() { you.normal_vision = LOS_DEFAULT_RANGE; int nom = 1; int denom = 1; // Barachi have +1 base LOS. if (you.species == SP_BARACHI) you.normal_vision += 1; // Nightstalker gives -1/-2/-3. if (you.get_mutation_level(MUT_NIGHTSTALKER)) { nom *= you.normal_vision - you.get_mutation_level(MUT_NIGHTSTALKER); denom *= you.normal_vision; } // the Darkness spell. if (you.duration[DUR_DARKNESS]) nom *= 3, denom *= 4; // robe of Night. if (player_equip_unrand(UNRAND_NIGHT)) nom *= 3, denom *= 4; you.current_vision = (you.normal_vision * nom + denom / 2) / denom; ASSERT(you.current_vision > 0); set_los_radius(you.current_vision); } /** * Ignoring form & most equipment, but not the UNRAND_FINGER_AMULET, can the * player use (usually wear) a given equipment slot? * * @param eq The slot in question. * @param temp Whether to consider forms. * @return MB_FALSE if the player can never use the slot; * MB_MAYBE if the player can only use some items for the slot; * MB_TRUE if the player can use any (fsvo any) item for the slot. */ maybe_bool you_can_wear(equipment_type eq, bool temp) { if (temp && !get_form()->slot_available(eq)) return MB_FALSE; switch (eq) { case EQ_LEFT_RING: if (you.get_mutation_level(MUT_MISSING_HAND)) return MB_FALSE; // intentional fallthrough case EQ_RIGHT_RING: return you.species != SP_OCTOPODE ? MB_TRUE : MB_FALSE; case EQ_RING_EIGHT: if (you.get_mutation_level(MUT_MISSING_HAND)) return MB_FALSE; // intentional fallthrough case EQ_RING_ONE: case EQ_RING_TWO: case EQ_RING_THREE: case EQ_RING_FOUR: case EQ_RING_FIVE: case EQ_RING_SIX: case EQ_RING_SEVEN: return you.species == SP_OCTOPODE ? MB_TRUE : MB_FALSE; case EQ_WEAPON: case EQ_STAFF: return you.species == SP_FELID ? MB_FALSE : you.body_size(PSIZE_TORSO, !temp) < SIZE_MEDIUM ? MB_MAYBE : MB_TRUE; // You can always wear at least one ring (forms were already handled). case EQ_RINGS: case EQ_ALL_ARMOUR: case EQ_AMULET: return MB_TRUE; case EQ_RING_AMULET: return player_equip_unrand(UNRAND_FINGER_AMULET) ? MB_TRUE : MB_FALSE; default: break; } item_def dummy, alternate; dummy.base_type = alternate.base_type = OBJ_ARMOUR; dummy.sub_type = alternate.sub_type = NUM_ARMOURS; // Make sure can_wear_armour doesn't think it's Lear's. dummy.unrand_idx = alternate.unrand_idx = 0; switch (eq) { case EQ_CLOAK: dummy.sub_type = ARM_CLOAK; alternate.sub_type = ARM_SCARF; break; case EQ_GLOVES: dummy.sub_type = ARM_GLOVES; break; case EQ_BOOTS: // And bardings dummy.sub_type = ARM_BOOTS; if (you.species == SP_NAGA) alternate.sub_type = ARM_NAGA_BARDING; if (you.species == SP_CENTAUR) alternate.sub_type = ARM_CENTAUR_BARDING; break; case EQ_BODY_ARMOUR: // Assume that anything that can wear any armour at all can wear a robe // and that anything that can wear CPA can wear all armour. dummy.sub_type = ARM_CRYSTAL_PLATE_ARMOUR; alternate.sub_type = ARM_ROBE; break; case EQ_SHIELD: // No races right now that can wear ARM_TOWER_SHIELD but not ARM_KITE_SHIELD dummy.sub_type = ARM_TOWER_SHIELD; if (you.body_size(PSIZE_TORSO, !temp) < SIZE_MEDIUM) alternate.sub_type = ARM_BUCKLER; break; case EQ_HELMET: dummy.sub_type = ARM_HELMET; alternate.sub_type = ARM_HAT; break; default: die("unhandled equipment type %d", eq); break; } ASSERT(dummy.sub_type != NUM_ARMOURS); if (can_wear_armour(dummy, false, !temp)) return MB_TRUE; else if (alternate.sub_type != NUM_ARMOURS && can_wear_armour(alternate, false, !temp)) { return MB_MAYBE; } else return MB_FALSE; } bool player_has_feet(bool temp, bool include_mutations) { if (you.species == SP_NAGA || you.species == SP_FELID || you.species == SP_OCTOPODE || you.fishtail && temp) { return false; } if (include_mutations && (you.get_mutation_level(MUT_HOOVES, temp) == 3 || you.get_mutation_level(MUT_TALONS, temp) == 3)) { return false; } return true; } // Returns false if the player is wielding a weapon inappropriate for Berserk. bool berserk_check_wielded_weapon() { const item_def * const wpn = you.weapon(); bool penance = false; if (wpn && wpn->defined() && (!is_melee_weapon(*wpn) || needs_handle_warning(*wpn, OPER_ATTACK, penance))) { string prompt = "Do you really want to go berserk while wielding " + wpn->name(DESC_YOUR) + "?"; if (penance) prompt += " This could place you under penance!"; if (!yesno(prompt.c_str(), true, 'n')) { canned_msg(MSG_OK); return false; } } return true; } // Looks in equipment "slot" to see if there is an equipped "sub_type". // Returns number of matches (in the case of rings, both are checked) int player::wearing(equipment_type slot, int sub_type, bool calc_unid) const { int ret = 0; const item_def* item; switch (slot) { case EQ_WEAPON: // Hands can have more than just weapons. if (weapon() && weapon()->is_type(OBJ_WEAPONS, sub_type)) ret++; break; case EQ_STAFF: // Like above, but must be magical staff. if (weapon() && weapon()->is_type(OBJ_STAVES, sub_type) && (calc_unid || item_type_known(*weapon()))) { ret++; } break; case EQ_AMULET: case EQ_AMULET_PLUS: if ((item = slot_item(static_cast<equipment_type>(EQ_AMULET))) && item->sub_type == sub_type && (calc_unid || item_type_known(*item))) { ret += (slot == EQ_AMULET_PLUS ? item->plus : 1); } break; case EQ_RINGS: case EQ_RINGS_PLUS: for (int slots = EQ_FIRST_JEWELLERY; slots <= EQ_LAST_JEWELLERY; slots++) { if (slots == EQ_AMULET) continue; if ((item = slot_item(static_cast<equipment_type>(slots))) && item->sub_type == sub_type && (calc_unid || item_type_known(*item))) { ret += (slot == EQ_RINGS_PLUS ? item->plus : 1); } } break; case EQ_ALL_ARMOUR: // Doesn't make much sense here... be specific. -- bwr die("EQ_ALL_ARMOUR is not a proper slot"); break; default: if (! (slot >= EQ_FIRST_EQUIP && slot < NUM_EQUIP)) die("invalid slot"); if ((item = slot_item(slot)) && item->sub_type == sub_type && (calc_unid || item_type_known(*item))) { ret++; } break; } return ret; } // Looks in equipment "slot" to see if equipped item has "special" ego-type // Returns number of matches (jewellery returns zero -- no ego type). // [ds] There's no equivalent of calc_unid or req_id because as of now, weapons // and armour type-id on wield/wear. int player::wearing_ego(equipment_type slot, int special, bool calc_unid) const { int ret = 0; const item_def* item; switch (slot) { case EQ_WEAPON: // Hands can have more than just weapons. if ((item = slot_item(EQ_WEAPON)) && item->base_type == OBJ_WEAPONS && get_weapon_brand(*item) == special) { ret++; } break; case EQ_LEFT_RING: case EQ_RIGHT_RING: case EQ_AMULET: case EQ_STAFF: case EQ_RINGS: case EQ_RINGS_PLUS: // no ego types for these slots break; case EQ_ALL_ARMOUR: // Check all armour slots: for (int i = EQ_MIN_ARMOUR; i <= EQ_MAX_ARMOUR; i++) { if ((item = slot_item(static_cast<equipment_type>(i))) && get_armour_ego_type(*item) == special && (calc_unid || item_type_known(*item))) { ret++; } } break; default: if (slot < EQ_MIN_ARMOUR || slot > EQ_MAX_ARMOUR) die("invalid slot: %d", slot); // Check a specific armour slot for an ego type: if ((item = slot_item(static_cast<equipment_type>(slot))) && get_armour_ego_type(*item) == special && (calc_unid || item_type_known(*item))) { ret++; } break; } return ret; } // Returns true if the indicated unrandart is equipped // [ds] There's no equivalent of calc_unid or req_id because as of now, weapons // and armour type-id on wield/wear. bool player_equip_unrand(int unrand_index) { const unrandart_entry* entry = get_unrand_entry(unrand_index); equipment_type slot = get_item_slot(entry->base_type, entry->sub_type); item_def* item; switch (slot) { case EQ_WEAPON: // Hands can have more than just weapons. if ((item = you.slot_item(slot)) && item->base_type == OBJ_WEAPONS && is_unrandom_artefact(*item) && item->unrand_idx == unrand_index) { return true; } break; case EQ_RINGS: for (int slots = EQ_FIRST_JEWELLERY; slots <= EQ_LAST_JEWELLERY; ++slots) { if (slots == EQ_AMULET) continue; if ((item = you.slot_item(static_cast<equipment_type>(slots))) && is_unrandom_artefact(*item) && item->unrand_idx == unrand_index) { return true; } } break; case EQ_NONE: case EQ_STAFF: case EQ_LEFT_RING: case EQ_RIGHT_RING: case EQ_RINGS_PLUS: case EQ_ALL_ARMOUR: // no unrandarts for these slots. break; default: if (slot <= EQ_NONE || slot >= NUM_EQUIP) die("invalid slot: %d", slot); // Check a specific slot. if ((item = you.slot_item(slot)) && is_unrandom_artefact(*item) && item->unrand_idx == unrand_index) { return true; } break; } return false; } bool player_can_hear(const coord_def& p, int hear_distance) { return !silenced(p) && !silenced(you.pos()) && you.pos().distance_from(p) <= hear_distance; } int player_teleport(bool calc_unid) { ASSERT(!crawl_state.game_is_arena()); // Don't allow any form of teleportation in Sprint or Gauntlets. if (crawl_state.game_is_sprint() || player_in_branch(BRANCH_GAUNTLET)) return 0; // Short-circuit rings of teleport to prevent spam. if (you.species == SP_FORMICID) return 0; int tp = 0; // rings (keep in sync with _equip_jewellery_effect) tp += 8 * you.wearing(EQ_RINGS, RING_TELEPORTATION, calc_unid); // artefacts tp += 8 * you.scan_artefacts(ARTP_CAUSE_TELEPORTATION, calc_unid); // mutations tp += you.get_mutation_level(MUT_TELEPORT) * 4; return tp; } // Computes bonuses to regeneration from most sources. Does not handle // slow regeneration, vampireness, or Trog's Hand. static int _player_bonus_regen() { int rr = 0; // Jewellery. if (you.props[REGEN_AMULET_ACTIVE].get_int() == 1) rr += REGEN_PIP * you.wearing(EQ_AMULET, AMU_REGENERATION); // Artefacts rr += REGEN_PIP * you.scan_artefacts(ARTP_REGENERATION); // Troll leather if (you.wearing(EQ_BODY_ARMOUR, ARM_TROLL_LEATHER_ARMOUR)) rr += REGEN_PIP; // Fast heal mutation. rr += you.get_mutation_level(MUT_REGENERATION) * REGEN_PIP; // Powered By Death mutation, boosts regen by variable strength // if the duration of the effect is still active. if (you.duration[DUR_POWERED_BY_DEATH]) rr += you.props[POWERED_BY_DEATH_KEY].get_int() * 100; return rr; } // Inhibited regeneration: stops regeneration when monsters are visible bool regeneration_is_inhibited() { if (you.get_mutation_level(MUT_INHIBITED_REGENERATION) == 1 || (you.species == SP_VAMPIRE && !you.vampire_alive)) { for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi) { if (mons_is_threatening(**mi) && !mi->wont_attack() && !mi->neutral() && !mi->submerged()) { return true; } } } return false; } int player_regen() { // Note: if some condition can set rr = 0, can't be rested off, and // would allow travel, please update is_sufficiently_rested. int rr = you.hp_max / 3; if (rr > 20) rr = 20 + ((rr - 20) / 2); // Add in miscellaneous bonuses rr += _player_bonus_regen(); // Before applying other effects, make sure that there's something // to heal. rr = max(1, rr); // Bonus regeneration for alive vampires. if (you.species == SP_VAMPIRE && you.vampire_alive) rr += 20; if (you.duration[DUR_COLLAPSE]) rr /= 4; if (you.disease || regeneration_is_inhibited() || !player_regenerates_hp()) rr = 0; // Trog's Hand. This circumvents sickness or inhibited regeneration. if (you.duration[DUR_TROGS_HAND]) rr += 100; return rr; } int player_mp_regen() { int regen_amount = 7 + you.max_magic_points / 2; if (you.get_mutation_level(MUT_MANA_REGENERATION)) regen_amount *= 2; if (you.props[MANA_REGEN_AMULET_ACTIVE].get_int() == 1) regen_amount += 25; return regen_amount; } // Some amulets need to be worn while at full health before they begin to // function. void update_amulet_attunement_by_health() { // amulet of regeneration // You must be wearing the amulet and able to regenerate to get benefits. if (you.wearing(EQ_AMULET, AMU_REGENERATION) && you.get_mutation_level(MUT_NO_REGENERATION) == 0) { // If you hit max HP, turn on the amulet. if (you.hp == you.hp_max && you.props[REGEN_AMULET_ACTIVE].get_int() == 0) { you.props[REGEN_AMULET_ACTIVE] = 1; mpr("Your amulet attunes itself to your body and you begin to " "regenerate more quickly."); } } else you.props[REGEN_AMULET_ACTIVE] = 0; // amulet of the acrobat if (you.wearing(EQ_AMULET, AMU_ACROBAT)) { if (you.hp == you.hp_max && you.props[ACROBAT_AMULET_ACTIVE].get_int() == 0) { you.props[ACROBAT_AMULET_ACTIVE] = 1; mpr("Your amulet attunes itself to your body. You feel like " "doing cartwheels."); } } else you.props[ACROBAT_AMULET_ACTIVE] = 0; } // Amulet of magic regeneration needs to be worn while at full magic before it // begins to function. void update_mana_regen_amulet_attunement() { if (you.wearing(EQ_AMULET, AMU_MANA_REGENERATION) && player_regenerates_mp()) { if (you.magic_points == you.max_magic_points && you.props[MANA_REGEN_AMULET_ACTIVE].get_int() == 0) { you.props[MANA_REGEN_AMULET_ACTIVE] = 1; mpr("Your amulet attunes itself to your body and you begin to " "regenerate magic more quickly."); } } else you.props[MANA_REGEN_AMULET_ACTIVE] = 0; } int player_hunger_rate() { int hunger = 3; if (you.species == SP_TROLL) hunger += 3; // in addition to the +3 for fast metabolism hunger += you.get_mutation_level(MUT_FAST_METABOLISM) - you.get_mutation_level(MUT_SLOW_METABOLISM); // If Cheibriados has slowed your life processes, you will hunger less. if (have_passive(passive_t::slow_metabolism)) hunger /= 2; if (hunger < 1) hunger = 1; return hunger; } /** * How many spell levels does the player have total, including those used up * by memorised spells? */ int player_total_spell_levels() { return you.experience_level - 1 + you.skill(SK_SPELLCASTING, 2, true); } /** * How many spell levels does the player currently have available for * memorising new spells? */ int player_spell_levels() { int sl = min(player_total_spell_levels(), 99); #if TAG_MAJOR_VERSION == 34 bool fireball = false; bool delayed_fireball = false; #endif for (const spell_type spell : you.spells) { #if TAG_MAJOR_VERSION == 34 if (spell == SPELL_FIREBALL) fireball = true; else if (spell == SPELL_DELAYED_FIREBALL) delayed_fireball = true; #endif if (spell != SPELL_NO_SPELL) sl -= spell_difficulty(spell); } #if TAG_MAJOR_VERSION == 34 // Fireball is free for characters with delayed fireball if (fireball && delayed_fireball) sl += spell_difficulty(SPELL_FIREBALL); #endif // Note: This can happen because of draining. -- bwr if (sl < 0) sl = 0; return sl; } bool player_likes_chunks(bool permanently) { return you.gourmand(true, !permanently) || you.get_mutation_level(MUT_CARNIVOROUS) > 0; } // If temp is set to false, temporary sources or resistance won't be counted. int player_res_fire(bool calc_unid, bool temp, bool items) { int rf = 0; if (items) { // rings of fire resistance/fire rf += you.wearing(EQ_RINGS, RING_PROTECTION_FROM_FIRE, calc_unid); rf += you.wearing(EQ_RINGS, RING_FIRE, calc_unid); // rings of ice rf -= you.wearing(EQ_RINGS, RING_ICE, calc_unid); // Staves rf += you.wearing(EQ_STAFF, STAFF_FIRE, calc_unid); // body armour: const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR); if (body_armour) rf += armour_type_prop(body_armour->sub_type, ARMF_RES_FIRE); // ego armours rf += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_FIRE_RESISTANCE); rf += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_RESISTANCE); // randart weapons: rf += you.scan_artefacts(ARTP_FIRE, calc_unid); // dragonskin cloak: 0.5 to draconic resistances if (calc_unid && player_equip_unrand(UNRAND_DRAGONSKIN) && coinflip()) { rf++; } } // species: if (you.species == SP_MUMMY) rf--; // mutations: rf += you.get_mutation_level(MUT_HEAT_RESISTANCE, temp); rf -= you.get_mutation_level(MUT_HEAT_VULNERABILITY, temp); rf -= you.get_mutation_level(MUT_TEMPERATURE_SENSITIVITY, temp); rf += you.get_mutation_level(MUT_MOLTEN_SCALES, temp) == 3 ? 1 : 0; // spells: if (temp) { if (you.duration[DUR_RESISTANCE]) rf++; if (you.duration[DUR_FIRE_SHIELD]) rf += 2; if (you.duration[DUR_QAZLAL_FIRE_RES]) rf++; rf += get_form()->res_fire(); } if (rf > 3) rf = 3; if (temp && you.duration[DUR_FIRE_VULN]) rf--; if (rf < -3) rf = -3; return rf; } int player_res_steam(bool calc_unid, bool temp, bool items) { int res = 0; const int rf = player_res_fire(calc_unid, temp, items); if (you.species == SP_PALE_DRACONIAN) res += 2; if (items) { const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR); if (body_armour) res += armour_type_prop(body_armour->sub_type, ARMF_RES_STEAM) * 2; } res += rf * 2; if (res > 2) res = 2; return res; } int player_res_cold(bool calc_unid, bool temp, bool items) { int rc = 0; if (temp) { if (you.duration[DUR_RESISTANCE]) rc++; if (you.duration[DUR_FIRE_SHIELD]) rc -= 2; if (you.duration[DUR_QAZLAL_COLD_RES]) rc++; rc += get_form()->res_cold(); if (you.species == SP_VAMPIRE && !you.vampire_alive) rc += 2; } if (items) { // rings of cold resistance/ice rc += you.wearing(EQ_RINGS, RING_PROTECTION_FROM_COLD, calc_unid); rc += you.wearing(EQ_RINGS, RING_ICE, calc_unid); // rings of fire rc -= you.wearing(EQ_RINGS, RING_FIRE, calc_unid); // Staves rc += you.wearing(EQ_STAFF, STAFF_COLD, calc_unid); // body armour: const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR); if (body_armour) rc += armour_type_prop(body_armour->sub_type, ARMF_RES_COLD); // ego armours rc += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_COLD_RESISTANCE); rc += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_RESISTANCE); // randart weapons: rc += you.scan_artefacts(ARTP_COLD, calc_unid); // dragonskin cloak: 0.5 to draconic resistances if (calc_unid && player_equip_unrand(UNRAND_DRAGONSKIN) && coinflip()) rc++; } // mutations: rc += you.get_mutation_level(MUT_COLD_RESISTANCE, temp); rc -= you.get_mutation_level(MUT_COLD_VULNERABILITY, temp); rc -= you.get_mutation_level(MUT_TEMPERATURE_SENSITIVITY, temp); rc += you.get_mutation_level(MUT_ICY_BLUE_SCALES, temp) == 3 ? 1 : 0; rc += you.get_mutation_level(MUT_SHAGGY_FUR, temp) == 3 ? 1 : 0; if (rc < -3) rc = -3; else if (rc > 3) rc = 3; return rc; } bool player::res_corr(bool calc_unid, bool items) const { // dragonskin cloak: 0.5 to draconic resistances if (items && calc_unid && player_equip_unrand(UNRAND_DRAGONSKIN) && coinflip()) { return true; } if (have_passive(passive_t::resist_corrosion)) return true; if (get_mutation_level(MUT_ACID_RESISTANCE)) return true; if (get_form()->res_acid()) return true; if (you.duration[DUR_RESISTANCE]) return true; // TODO: why doesn't this use the usual form suppression mechanism? if (form_keeps_mutations() && get_mutation_level(MUT_YELLOW_SCALES) >= 3) { return true; } return actor::res_corr(calc_unid, items); } int player_res_acid(bool calc_unid, bool items) { return you.res_corr(calc_unid, items) ? 1 : 0; } int player_res_electricity(bool calc_unid, bool temp, bool items) { int re = 0; if (items) { // staff re += you.wearing(EQ_STAFF, STAFF_AIR, calc_unid); // body armour: const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR); if (body_armour) re += armour_type_prop(body_armour->sub_type, ARMF_RES_ELEC); // randart weapons: re += you.scan_artefacts(ARTP_ELECTRICITY, calc_unid); // dragonskin cloak: 0.5 to draconic resistances if (calc_unid && player_equip_unrand(UNRAND_DRAGONSKIN) && coinflip()) re++; } // mutations: re += you.get_mutation_level(MUT_THIN_METALLIC_SCALES, temp) == 3 ? 1 : 0; re += you.get_mutation_level(MUT_SHOCK_RESISTANCE, temp); re -= you.get_mutation_level(MUT_SHOCK_VULNERABILITY, temp); if (temp) { if (you.duration[DUR_RESISTANCE]) re++; if (you.duration[DUR_QAZLAL_ELEC_RES]) re++; // transformations: if (get_form()->res_elec()) re++; } if (re > 1) re = 1; return re; } /** * Is the player character immune to torment? * * @param random Whether to include unreliable effects (stochastic resist) * @return Whether the player resists a given instance of torment; if * random is passed, the result may vary from call to call. */ bool player_res_torment(bool random) { if (you.get_mutation_level(MUT_TORMENT_RESISTANCE)) return true; if (random && you.get_mutation_level(MUT_STOCHASTIC_TORMENT_RESISTANCE) && coinflip()) { return true; } return get_form()->res_neg() == 3 || you.species == SP_VAMPIRE && !you.vampire_alive || you.petrified() #if TAG_MAJOR_VERSION == 34 || player_equip_unrand(UNRAND_ETERNAL_TORMENT) #endif ; } // Kiku protects you from torment to a degree. bool player_kiku_res_torment() { // no protection during pain branding weapon return have_passive(passive_t::resist_torment) && !(you_worship(GOD_KIKUBAAQUDGHA) && you.gift_timeout); } // If temp is set to false, temporary sources or resistance won't be counted. int player_res_poison(bool calc_unid, bool temp, bool items) { switch (you.undead_state(temp)) { case US_ALIVE: break; case US_HUNGRY_DEAD: //ghouls case US_UNDEAD: // mummies & lichform return 3; case US_SEMI_UNDEAD: // vampire if (!you.vampire_alive) // XXX: && temp? return 3; break; } if (you.is_nonliving(temp) || temp && get_form()->res_pois() == 3 || items && player_equip_unrand(UNRAND_OLGREB) || temp && you.duration[DUR_DIVINE_STAMINA]) { return 3; } int rp = 0; if (items) { // rings of poison resistance rp += you.wearing(EQ_RINGS, RING_POISON_RESISTANCE, calc_unid); // Staves rp += you.wearing(EQ_STAFF, STAFF_POISON, calc_unid); // ego armour: rp += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_POISON_RESISTANCE); // body armour: const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR); if (body_armour) rp += armour_type_prop(body_armour->sub_type, ARMF_RES_POISON); // rPois+ artefacts rp += you.scan_artefacts(ARTP_POISON, calc_unid); // dragonskin cloak: 0.5 to draconic resistances if (calc_unid && player_equip_unrand(UNRAND_DRAGONSKIN) && coinflip()) rp++; } // mutations: rp += you.get_mutation_level(MUT_POISON_RESISTANCE, temp); rp += you.get_mutation_level(MUT_SLIMY_GREEN_SCALES, temp) == 3 ? 1 : 0; if (temp) { // potions/cards: if (you.duration[DUR_RESISTANCE]) rp++; if (get_form()->res_pois() > 0) rp++; } // Cap rPois at + before vulnerability effects are applied // (so carrying multiple rPois effects is never useful) rp = min(1, rp); if (temp) { if (get_form()->res_pois() < 0) rp--; if (you.duration[DUR_POISON_VULN]) rp--; } // don't allow rPois--, etc. rp = max(-1, rp); return rp; } int player_res_sticky_flame() { return get_form()->res_sticky_flame(); } int player_spec_death() { int sd = 0; // Staves sd += you.wearing(EQ_STAFF, STAFF_DEATH); // species: sd += you.get_mutation_level(MUT_NECRO_ENHANCER); // transformations: if (you.form == transformation::lich) sd++; return sd; } int player_spec_fire() { int sf = 0; // staves: sf += you.wearing(EQ_STAFF, STAFF_FIRE); // rings of fire: sf += you.wearing(EQ_RINGS, RING_FIRE); if (you.duration[DUR_FIRE_SHIELD]) sf++; if (player_equip_unrand(UNRAND_ELEMENTAL_STAFF)) sf++; return sf; } int player_spec_cold() { int sc = 0; // staves: sc += you.wearing(EQ_STAFF, STAFF_COLD); // rings of ice: sc += you.wearing(EQ_RINGS, RING_ICE); if (player_equip_unrand(UNRAND_ELEMENTAL_STAFF)) sc++; return sc; } int player_spec_earth() { int se = 0; // Staves se += you.wearing(EQ_STAFF, STAFF_EARTH); if (player_equip_unrand(UNRAND_ELEMENTAL_STAFF)) se++; return se; } int player_spec_air() { int sa = 0; // Staves sa += you.wearing(EQ_STAFF, STAFF_AIR); if (player_equip_unrand(UNRAND_ELEMENTAL_STAFF)) sa++; return sa; } int player_spec_conj() { int sc = 0; // Staves sc += you.wearing(EQ_STAFF, STAFF_CONJURATION); if (player_equip_unrand(UNRAND_BATTLE)) sc++; return sc; } int player_spec_hex() { return 0; } int player_spec_charm() { // Nothing, for the moment. return 0; } int player_spec_summ() { int ss = 0; // Staves ss += you.wearing(EQ_STAFF, STAFF_SUMMONING); return ss; } int player_spec_poison() { int sp = 0; // Staves sp += you.wearing(EQ_STAFF, STAFF_POISON); if (player_equip_unrand(UNRAND_OLGREB)) sp++; return sp; } bool hungerless_spells() { return you.wearing(EQ_STAFF, STAFF_ENERGY) || you.duration[DUR_BRILLIANCE]; } // If temp is set to false, temporary sources of resistance won't be // counted. int player_prot_life(bool calc_unid, bool temp, bool items) { int pl = 0; // Hunger is temporary, true, but that's something you can control, // especially as life protection only increases the hungrier you // get. if (you.species == SP_VAMPIRE && !you.vampire_alive) pl = 3; // Same here. Your piety status, and, hence, TSO's protection, is // something you can more or less control. if (you_worship(GOD_SHINING_ONE)) { if (you.piety >= piety_breakpoint(1)) pl++; if (you.piety >= piety_breakpoint(3)) pl++; if (you.piety >= piety_breakpoint(5)) pl++; } if (temp) { pl += get_form()->res_neg(); // completely stoned, unlike statue which has some life force if (you.petrified()) pl += 3; } if (items) { // rings pl += you.wearing(EQ_RINGS, RING_LIFE_PROTECTION, calc_unid); // armour (checks body armour only) pl += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_POSITIVE_ENERGY); // pearl dragon counts const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR); if (body_armour) pl += armour_type_prop(body_armour->sub_type, ARMF_RES_NEG); // randart wpns pl += you.scan_artefacts(ARTP_NEGATIVE_ENERGY, calc_unid); // dragonskin cloak: 0.5 to draconic resistances if (calc_unid && player_equip_unrand(UNRAND_DRAGONSKIN) && coinflip()) pl++; pl += you.wearing(EQ_STAFF, STAFF_DEATH, calc_unid); } // undead/demonic power pl += you.get_mutation_level(MUT_NEGATIVE_ENERGY_RESISTANCE, temp); pl = min(3, pl); return pl; } // New player movement speed system... allows for a bit more than // "player runs fast" and "player walks slow" in that the speed is // actually calculated (allowing for centaurs to get a bonus from // swiftness and other such things). Levels of the mutation now // also have meaning (before they all just meant fast). Most of // this isn't as fast as it used to be (6 for having anything), but // even a slight speed advantage is very good... and we certainly don't // want to go past 6 (see below). -- bwr int player_movement_speed() { int mv = 10; // transformations if (you.form == transformation::bat) mv = 5; // but allowed minimum is six else if (you.form == transformation::pig) mv = 7; else if (you.form == transformation::wisp) mv = 8; else if (you.fishtail || you.form == transformation::hydra && you.in_water()) mv = 6; // Wading through water is very slow. if (you.in_water() && !you.can_swim() || you.liquefied_ground() && !you.duration[DUR_LIQUEFYING]) { mv += 6; } // armour if (you.run()) mv -= 1; mv += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_PONDEROUSNESS); // Cheibriados if (have_passive(passive_t::slowed)) mv += 2 + min(div_rand_round(you.piety, 20), 8); else if (player_under_penance(GOD_CHEIBRIADOS)) mv += 2 + min(div_rand_round(you.piety_max[GOD_CHEIBRIADOS], 20), 8); // Tengu can move slightly faster when flying. if (you.tengu_flight()) mv--; if (you.duration[DUR_FROZEN]) mv += 3; // Mutations: -2, -3, -4, unless innate and shapechanged. if (int fast = you.get_mutation_level(MUT_FAST)) mv -= fast + 1; if (int slow = you.get_mutation_level(MUT_SLOW)) { mv *= 10 + slow * 2; mv /= 10; } if (you.duration[DUR_SWIFTNESS] > 0 && !you.in_liquid()) { if (you.attribute[ATTR_SWIFTNESS] > 0) mv = div_rand_round(3*mv, 4); else if (mv >= 8) mv = div_rand_round(3*mv, 2); else if (mv == 7) mv = div_rand_round(7*6, 5); // balance for the cap at 6 } // We'll use the old value of six as a minimum, with haste this could // end up as a speed of three, which is about as fast as we want // the player to be able to go (since 3 is 3.33x as fast and 2 is 5x, // which is a bit of a jump, and a bit too fast) -- bwr // Currently Haste takes 6 to 4, which is 2.5x as fast as delay 10 // and still seems plenty fast. -- elliptic if (mv < FASTEST_PLAYER_MOVE_SPEED) mv = FASTEST_PLAYER_MOVE_SPEED; return mv; } /** * Multiply the power of some evocation per the player's current evocations * enhancers. * * @param power The base power of the evocation. * @param enhancers Bonus enhancers to evocations (pak device surge). * @return A modified power value. */ int player_adjust_evoc_power(const int power, int enhancers) { const int total_enhancers = you.spec_evoke() + enhancers; return stepdown_spellpower(100 *apply_enhancement(power, total_enhancers)); } // This function differs from the above in that it's used to set the // initial time_taken value for the turn. Everything else (movement, // spellcasting, combat) applies a ratio to this value. int player_speed() { int ps = 10; // When paralysed, speed is irrelevant. if (you.cannot_act()) return ps; if (you.duration[DUR_SLOW] || have_stat_zero()) ps = haste_mul(ps); if (you.duration[DUR_BERSERK] && !have_passive(passive_t::no_haste)) ps = berserk_div(ps); else if (you.duration[DUR_HASTE]) ps = haste_div(ps); if (you.form == transformation::statue || you.duration[DUR_PETRIFYING]) { ps *= 15; ps /= 10; } return ps; } bool is_effectively_light_armour(const item_def *item) { return !item || (abs(property(*item, PARM_EVASION)) / 10 < 5); } bool player_effectively_in_light_armour() { const item_def *armour = you.slot_item(EQ_BODY_ARMOUR, false); return is_effectively_light_armour(armour); } // This function returns true if the player has a radically different // shape... minor changes like blade hands don't count, also note // that lich transformation doesn't change the character's shape // (so we end up with Naga-liches, Spriggan-liches, Minotaur-liches) // it just makes the character undead (with the benefits that implies). - bwr bool player_is_shapechanged() { if (you.form == transformation::none || you.form == transformation::blade_hands || you.form == transformation::lich || you.form == transformation::shadow || you.form == transformation::appendage) { return false; } return true; } void update_acrobat_status() { if (you.props[ACROBAT_AMULET_ACTIVE].get_int() != 1) return; // Acrobat duration goes slightly into the next turn, giving the // player visual feedback of the EV bonus recieved. // This is assignment and not increment as acrobat duration depends // on player action. you.duration[DUR_ACROBAT] = you.time_taken+1; you.redraw_evasion = true; } // An evasion factor based on the player's body size, smaller == higher // evasion size factor. static int _player_evasion_size_factor(bool base = false) { // XXX: you.body_size() implementations are incomplete, fix. const size_type size = you.body_size(PSIZE_BODY, base); return 2 * (SIZE_MEDIUM - size); } // Determines racial shield penalties (formicids get a bonus compared to // other medium-sized races) int player_shield_racial_factor() { return max(1, 5 + (you.species == SP_FORMICID ? -2 // Same as trolls/centaurs/etc. : _player_evasion_size_factor(true))); } // The total EV penalty to the player for all their worn armour items // with a base EV penalty (i.e. EV penalty as a base armour property, // not as a randart property). static int _player_adjusted_evasion_penalty(const int scale) { int piece_armour_evasion_penalty = 0; // Some lesser armours have small penalties now (barding). for (int i = EQ_MIN_ARMOUR; i < EQ_MAX_ARMOUR; i++) { if (i == EQ_SHIELD || !you.slot_item(static_cast<equipment_type>(i))) continue; // [ds] Evasion modifiers for armour are negatives, change // those to positive for penalty calc. const int penalty = (-property(you.inv[you.equip[i]], PARM_EVASION))/3; if (penalty > 0) piece_armour_evasion_penalty += penalty; } return piece_armour_evasion_penalty * scale / 10 + you.adjusted_body_armour_penalty(scale); } // Player EV bonuses for various effects and transformations. This // does not include tengu/merfolk EV bonuses for flight/swimming. static int _player_evasion_bonuses() { int evbonus = 0; if (you.duration[DUR_AGILITY]) evbonus += AGILITY_BONUS; evbonus += you.wearing(EQ_RINGS_PLUS, RING_EVASION); evbonus += you.scan_artefacts(ARTP_EVASION); // mutations evbonus += you.get_mutation_level(MUT_GELATINOUS_BODY); if (you.get_mutation_level(MUT_DISTORTION_FIELD)) evbonus += you.get_mutation_level(MUT_DISTORTION_FIELD) + 1; // transformation penalties/bonuses not covered by size alone: if (you.get_mutation_level(MUT_SLOW_REFLEXES)) evbonus -= you.get_mutation_level(MUT_SLOW_REFLEXES) * 5; // If you have an active amulet of the acrobat and just moved or waited, get massive // EV bonus. if (acrobat_boost_active()) evbonus += 15; return evbonus; } // Player EV scaling for being flying tengu or swimming merfolk. static int _player_scale_evasion(int prescaled_ev, const int scale) { if (you.duration[DUR_PETRIFYING] || you.caught()) prescaled_ev /= 2; // Merfolk get a 25% evasion bonus in water. if (you.fishtail) { const int ev_bonus = max(2 * scale, prescaled_ev / 4); return prescaled_ev + ev_bonus; } // Flying Tengu get a 20% evasion bonus. if (you.tengu_flight()) { const int ev_bonus = max(1 * scale, prescaled_ev / 5); return prescaled_ev + ev_bonus; } return prescaled_ev; } /** * What is the player's bonus to EV from dodging when not paralysed, after * accounting for size & body armour penalties? * * First, calculate base dodge bonus (linear with dodging * stepdowned dex), * and armour dodge penalty (base armour evp, increased for small races & * decreased for large, then with a magic "3" subtracted from it to make the * penalties not too harsh). * * If the player's strength is greater than the armour dodge penalty, return * base dodge * (1 - dodge_pen / (str*2)). * E.g., if str is twice dodge penalty, return 3/4 of base dodge. If * str = dodge_pen * 4, return 7/8... * * If str is less than dodge penalty, return * base_dodge * str / (dodge_pen * 2). * E.g., if str = dodge_pen / 2, return 1/4 of base dodge. if * str = dodge_pen / 4, return 1/8... * * For either equation, if str = dodge_pen, the result is base_dodge/2. * * @param scale A scale to multiply the result by, to avoid precision loss. * @return A bonus to EV, multiplied by the scale. */ static int _player_armour_adjusted_dodge_bonus(int scale) { const int ev_dex = stepdown(you.dex(), 18, ROUND_CLOSE, MAX_STAT_VALUE); const int dodge_bonus = (70 + you.skill(SK_DODGING, 10) * ev_dex) * scale / (20 - _player_evasion_size_factor()) / 10; const int armour_dodge_penalty = you.unadjusted_body_armour_penalty() - 3; if (armour_dodge_penalty <= 0) return dodge_bonus; const int str = max(1, you.strength()); if (armour_dodge_penalty >= str) return dodge_bonus * str / (armour_dodge_penalty * 2); return dodge_bonus - dodge_bonus * armour_dodge_penalty / (str * 2); } // Total EV for player using the revised 0.6 evasion model. static int _player_evasion(ev_ignore_type evit) { const int size_factor = _player_evasion_size_factor(); // Size is all that matters when paralysed or at 0 dex. if ((you.cannot_move() || you.duration[DUR_CLUMSY] || you.form == transformation::tree) && !(evit & ev_ignore::helpless)) { return max(1, 2 + size_factor / 2); } const int scale = 100; const int size_base_ev = (10 + size_factor) * scale; const int vertigo_penalty = you.duration[DUR_VERTIGO] ? 5 * scale : 0; const int prestepdown_evasion = size_base_ev + _player_armour_adjusted_dodge_bonus(scale) - _player_adjusted_evasion_penalty(scale) - you.adjusted_shield_penalty(scale) - vertigo_penalty; const int poststepdown_evasion = stepdown_value(prestepdown_evasion, 20*scale, 30*scale, 60*scale, -1); const int evasion_bonuses = _player_evasion_bonuses() * scale; const int final_evasion = _player_scale_evasion(poststepdown_evasion, scale) + evasion_bonuses; return unscale_round_up(final_evasion, scale); } // Returns the spellcasting penalty (increase in spell failure) for the // player's worn body armour and shield. int player_armour_shield_spell_penalty() { const int scale = 100; const int body_armour_penalty = max(19 * you.adjusted_body_armour_penalty(scale), 0); const int total_penalty = body_armour_penalty + 19 * you.adjusted_shield_penalty(scale); return max(total_penalty, 0) / scale; } /** * How many spell-success-chance-boosting ('wizardry') effects can the player * apply to the given spell? * * @param spell The type of spell being cast. * @return The number of relevant wizardry effects. */ int player_wizardry(spell_type /*spell*/) { return you.wearing(EQ_RINGS, RING_WIZARDRY) + you.wearing(EQ_STAFF, STAFF_WIZARDRY); } /** * Calculate the SH value used internally. * * Exactly twice the value displayed to players, for legacy reasons. * @return The player's current SH value. */ int player_shield_class() { int shield = 0; if (you.incapacitated()) return 0; if (you.shield()) { const item_def& item = you.inv[you.equip[EQ_SHIELD]]; int size_factor = (you.body_size(PSIZE_TORSO) - SIZE_MEDIUM) * (item.sub_type - ARM_TOWER_SHIELD); int base_shield = property(item, PARM_AC) * 2 + size_factor; // bonus applied only to base, see above for effect: shield += base_shield * 50; shield += base_shield * you.skill(SK_SHIELDS, 5) / 2; shield += item.plus * 200; shield += you.skill(SK_SHIELDS, 38) + min(you.skill(SK_SHIELDS, 38), 3 * 38); int stat = 0; if (item.sub_type == ARM_BUCKLER) stat = you.dex() * 38; else if (item.sub_type == ARM_TOWER_SHIELD) stat = you.dex() * 12 + you.strength() * 26; else stat = you.dex() * 19 + you.strength() * 19; stat = stat * (base_shield + 13) / 26; shield += stat; } // mutations // +4, +6, +8 (displayed values) shield += (you.get_mutation_level(MUT_LARGE_BONE_PLATES) > 0 ? you.get_mutation_level(MUT_LARGE_BONE_PLATES) * 400 + 400 : 0); shield += qazlal_sh_boost() * 100; shield += tso_sh_boost() * 100; shield += you.wearing(EQ_AMULET_PLUS, AMU_REFLECTION) * 200; shield += you.scan_artefacts(ARTP_SHIELDING) * 200; return (shield + 50) / 100; } /** * Calculate the SH value that should be displayed to players. * * Exactly half the internal value, for legacy reasons. * @return The SH value to be displayed. */ int player_displayed_shield_class() { return player_shield_class() / 2; } /** * Does the player have 'omnireflection' (the ability to reflect piercing * effects and enchantments)? * * @return Whether the player has the Warlock's Mirror equipped. */ bool player_omnireflects() { return player_equip_unrand(UNRAND_WARLOCK_MIRROR); } void forget_map(bool rot) { ASSERT(!crawl_state.game_is_arena()); // If forgetting was intentional, clear the travel trail. if (!rot) clear_travel_trail(); const bool rot_resist = player_in_branch(BRANCH_ABYSS) && have_passive(passive_t::map_rot_res_abyss); const double geometric_chance = 0.99; const int radius = (rot_resist ? 200 : 100); const int scalar = 0xFF; for (rectangle_iterator ri(0); ri; ++ri) { const coord_def &p = *ri; if (!env.map_knowledge(p).known() || you.see_cell(p)) continue; if (rot) { const int dist = grid_distance(you.pos(), p); int chance = pow(geometric_chance, max(1, (dist * dist - radius) / 40)) * scalar; if (x_chance_in_y(chance, scalar)) continue; } if (you.see_cell(p)) continue; env.map_knowledge(p).clear(); if (env.map_forgotten) (*env.map_forgotten)(p).clear(); StashTrack.update_stash(p); #ifdef USE_TILE tile_forget_map(p); #endif } ash_detect_portals(is_map_persistent()); #ifdef USE_TILE tiles.update_minimap_bounds(); #endif } static void _recover_stat() { FixedVector<int, NUM_STATS> recovered_stats(0); while (you.attribute[ATTR_STAT_LOSS_XP] <= 0) { stat_type stat = random_lost_stat(); ASSERT(stat != NUM_STATS); recovered_stats[stat]++; // Very heavily drained stats recover faster. if (you.stat(stat, false) < 0) recovered_stats[stat] += random2(-you.stat(stat, false) / 2); bool still_drained = false; for (int i = 0; i < NUM_STATS; ++i) if (you.stat_loss[i] - recovered_stats[i] > 0) still_drained = true; if (still_drained) you.attribute[ATTR_STAT_LOSS_XP] += stat_loss_roll(); else break; } for (int i = 0; i < NUM_STATS; ++i) if (recovered_stats[i] > 0) restore_stat((stat_type) i, recovered_stats[i], false, true); } int get_exp_progress() { if (you.experience_level >= you.get_max_xl()) return 0; const int current = exp_needed(you.experience_level); const int next = exp_needed(you.experience_level + 1); if (next == current) return 0; return (you.experience - current) * 100 / (next - current); } static void _recharge_xp_evokers(int exp) { FixedVector<item_def*, NUM_MISCELLANY> evokers(nullptr); list_charging_evokers(evokers); int xp_factor = max(min((int)exp_needed(you.experience_level+1, 0) * 2 / 7, you.experience_level * 425), you.experience_level*4 + 30) / (3 + you.skill_rdiv(SK_EVOCATIONS, 2, 13)); for (int i = 0; i < NUM_MISCELLANY; ++i) { item_def* evoker = evokers[i]; if (!evoker) continue; int &debt = evoker_debt(evoker->sub_type); if (debt == 0) continue; const int old_charges = evoker_charges(i); debt = max(0, debt - div_rand_round(exp, xp_factor)); const int gained = evoker_charges(i) - old_charges; if (!gained) continue; if (evoker_max_charges(i) == 1) mprf("%s has recharged.", evoker->name(DESC_YOUR).c_str()); else { mprf("%s has regained %s charge%s.", evoker->name(DESC_YOUR).c_str(), number_in_words(gained).c_str(), gained > 1 ? "s" : ""); } } } /// Make progress toward the abyss spawning an exit/stairs. static void _reduce_abyss_xp_timer(int exp) { if (!player_in_branch(BRANCH_ABYSS)) return; const int xp_factor = max(min((int)exp_needed(you.experience_level+1, 0) / 7, you.experience_level * 425), you.experience_level*2 + 15) / 5; if (!you.props.exists(ABYSS_STAIR_XP_KEY)) you.props[ABYSS_STAIR_XP_KEY] = EXIT_XP_COST; const int reqd_xp = you.props[ABYSS_STAIR_XP_KEY].get_int(); const int new_req = reqd_xp - div_rand_round(exp, xp_factor); dprf("reducing xp timer from %d to %d (factor = %d)", reqd_xp, new_req, xp_factor); you.props[ABYSS_STAIR_XP_KEY].get_int() = new_req; } /// update penance for XP based gods static void _handle_xp_penance(int exp) { vector<god_type> xp_gods; for (god_iterator it; it; ++it) { if (xp_penance(*it)) xp_gods.push_back(*it); } if (!xp_gods.empty()) { god_type god = xp_gods[random2(xp_gods.size())]; reduce_xp_penance(god, exp); } } /// update transfer knowledge static void _transfer_knowledge(int exp) { if (!(you.transfer_skill_points > 0)) return; // Can happen if the game got interrupted during target skill choice. if (is_invalid_skill(you.transfer_to_skill)) { you.transfer_from_skill = SK_NONE; you.transfer_skill_points = 0; you.transfer_total_skill_points = 0; } else { int amount = exp * 20 / calc_skill_cost(you.skill_cost_level); if (amount >= 20 || one_chance_in(20 - amount)) { amount = max(20, amount); transfer_skill_points(you.transfer_from_skill, you.transfer_to_skill, amount, false); } } } /// update temporary mutations static void _handle_temp_mutation(int exp) { if (!(you.attribute[ATTR_TEMP_MUTATIONS] > 0)) return; you.attribute[ATTR_TEMP_MUT_XP] -= exp; if (you.attribute[ATTR_TEMP_MUT_XP] <= 0) temp_mutation_wanes(); } /// update stat loss static void _handle_stat_loss(int exp) { if (!(you.attribute[ATTR_STAT_LOSS_XP] > 0)) return; int loss = div_rand_round(exp * 3 / 2, max(1, calc_skill_cost(you.skill_cost_level) - 3)); you.attribute[ATTR_STAT_LOSS_XP] -= loss; dprf("Stat loss points: %d", you.attribute[ATTR_STAT_LOSS_XP]); if (you.attribute[ATTR_STAT_LOSS_XP] <= 0) _recover_stat(); } /// update xp drain static void _handle_xp_drain(int exp) { if (!you.attribute[ATTR_XP_DRAIN]) return; int loss = div_rand_round(exp * 3 / 2, calc_skill_cost(you.skill_cost_level)); // Make it easier to recover from very heavy levels of draining // (they're nasty enough as it is) loss = loss * (1 + (you.attribute[ATTR_XP_DRAIN] / 250.0f)); dprf("Lost %d of %d draining points", loss, you.attribute[ATTR_XP_DRAIN]); you.attribute[ATTR_XP_DRAIN] -= loss; // Regaining skills may affect AC/EV. you.redraw_armour_class = true; you.redraw_evasion = true; if (you.attribute[ATTR_XP_DRAIN] <= 0) { you.attribute[ATTR_XP_DRAIN] = 0; mprf(MSGCH_RECOVERY, "Your life force feels restored."); } } static void _handle_god_wrath(int exp) { for (god_iterator it; it; ++it) { if (active_penance(*it)) { you.attribute[ATTR_GOD_WRATH_XP] -= exp; while (you.attribute[ATTR_GOD_WRATH_XP] < 0) { you.attribute[ATTR_GOD_WRATH_COUNT]++; set_penance_xp_timeout(); } break; } } } void gain_exp(unsigned int exp_gained, unsigned int* actual_gain) { if (crawl_state.game_is_arena()) return; // xp-gated effects that don't use sprint inflation _handle_xp_penance(exp_gained); _handle_god_wrath(exp_gained); _transfer_knowledge(exp_gained); // evolution mutation timer you.attribute[ATTR_EVOL_XP] += exp_gained; // modified experience due to sprint inflation unsigned int skill_xp = exp_gained; if (crawl_state.game_is_sprint()) skill_xp = sprint_modify_exp(skill_xp); // xp-gated effects that use sprint inflation _handle_stat_loss(skill_xp); _handle_temp_mutation(skill_xp); _recharge_xp_evokers(skill_xp); _reduce_abyss_xp_timer(skill_xp); _handle_xp_drain(skill_xp); if (player_under_penance(GOD_HEPLIAKLQANA)) return; // no xp for you! // handle actual experience gains, // i.e. XL and skills const unsigned int old_exp = you.experience; dprf("gain_exp: %d", exp_gained); if (you.experience + exp_gained > (unsigned int)MAX_EXP_TOTAL) you.experience = MAX_EXP_TOTAL; else you.experience += exp_gained; you.exp_available += 10 * skill_xp; train_skills(); while (check_selected_skills() && you.exp_available >= calc_skill_cost(you.skill_cost_level)) { train_skills(); } level_change(); if (actual_gain != nullptr) *actual_gain = you.experience - old_exp; } bool will_gain_life(int lev) { if (lev < you.attribute[ATTR_LIFE_GAINED] - 2) return false; return you.lives + you.deaths < (lev - 1) / 3; } static void _felid_extra_life() { if (will_gain_life(you.max_level) && you.lives < 2) { you.lives++; mprf(MSGCH_INTRINSIC_GAIN, "Extra life!"); you.attribute[ATTR_LIFE_GAINED] = you.max_level; // Should play the 1UP sound from SMB... } } static void _gain_and_note_hp_mp() { const int old_mp = you.magic_points; const int old_maxmp = you.max_magic_points; // recalculate for game calc_hp(true, false); calc_mp(); set_mp(old_maxmp > 0 ? old_mp * you.max_magic_points / old_maxmp : you.max_magic_points); // Get "real" values for note-taking, i.e. ignore Berserk, // transformations or equipped items. const int note_maxhp = get_real_hp(false, true); const int note_maxmp = get_real_mp(false); char buf[200]; sprintf(buf, "HP: %d/%d MP: %d/%d", min(you.hp, note_maxhp), note_maxhp, min(you.magic_points, note_maxmp), note_maxmp); take_note(Note(NOTE_XP_LEVEL_CHANGE, you.experience_level, 0, buf)); } /** * Calculate max HP changes and scale current HP accordingly. */ void calc_hp(bool scale, bool set) { // Rounding must be down or Deep Dwarves would abuse certain values. // We can reduce errors by a factor of 100 by using partial hp we have. int oldhp = you.hp; int old_max = you.hp_max; you.hp_max = get_real_hp(true, true); if (scale) { int hp = you.hp * 100 + you.hit_points_regeneration; int new_max = you.hp_max; hp = hp * new_max / old_max; if (hp < 100) hp = 100; set_hp(min(hp / 100, you.hp_max)); you.hit_points_regeneration = hp % 100; } if (set) you.hp = you.hp_max; you.hp = min(you.hp, you.hp_max); if (oldhp != you.hp || old_max != you.hp_max) { dprf("HP changed: %d/%d -> %d/%d", oldhp, old_max, you.hp, you.hp_max); you.redraw_hit_points = true; } } int xp_to_level_diff(int xp, int scale) { ASSERT(xp >= 0); const int adjusted_xp = you.experience + xp; int projected_level = you.experience_level; while (you.experience >= exp_needed(projected_level + 1)) projected_level++; // handle xl 27 chars int adjusted_level = projected_level; // closest whole number level, rounding down while (adjusted_xp >= (int) exp_needed(adjusted_level + 1)) adjusted_level++; if (scale > 1) { // TODO: what is up with all the casts here? // decimal scaled version of current level including whatever fractional // part scale can handle const int cur_level_scaled = projected_level * scale + (you.experience - (int) exp_needed(projected_level)) * scale / ((int) exp_needed(projected_level + 1) - (int) exp_needed(projected_level)); // decimal scaled version of what adjusted_xp would get you const int adjusted_level_scaled = adjusted_level * scale + (adjusted_xp - (int) exp_needed(adjusted_level)) * scale / ((int) exp_needed(adjusted_level + 1) - (int) exp_needed(adjusted_level)); // TODO: this would be more usable with better rounding behaviour return adjusted_level_scaled - cur_level_scaled; } else return adjusted_level - projected_level; } /** * Handle the effects from a player's change in XL. * @param aux A string describing the cause of the level * change. * @param skip_attribute_increase If true and XL has increased, don't process * stat gains. Currently only used by wizmode * commands. */ void level_change(bool skip_attribute_increase) { // necessary for the time being, as level_change() is called // directly sometimes {dlb} you.redraw_experience = true; while (you.experience < exp_needed(you.experience_level)) lose_level(); while (you.experience_level < you.get_max_xl() && you.experience >= exp_needed(you.experience_level + 1)) { if (!skip_attribute_increase) { crawl_state.cancel_cmd_all(); if (is_processing_macro()) flush_input_buffer(FLUSH_ABORT_MACRO); } // [ds] Make sure we increment you.experience_level and apply // any stat/hp increases only after we've cleared all prompts // for this experience level. If we do part of the work before // the prompt, and a player on telnet gets disconnected, the // SIGHUP will save Crawl in the in-between state and rob the // player of their level-up perks. const int new_exp = you.experience_level + 1; // some species need to do this at a specific time; most just do it at the end bool updated_maxhp = false; if (new_exp <= you.max_level) { mprf(MSGCH_INTRINSIC_GAIN, "Welcome back to level %d!", new_exp); // No more prompts for this XL past this point. you.experience_level = new_exp; } else // Character has gained a new level { // Don't want to see the dead creature at the prompt. redraw_screen(); if (new_exp == 27) mprf(MSGCH_INTRINSIC_GAIN, "You have reached level 27, the final one!"); else if (new_exp == you.get_max_xl()) mprf(MSGCH_INTRINSIC_GAIN, "You have reached level %d, the highest you will ever reach!", you.get_max_xl()); else { mprf(MSGCH_INTRINSIC_GAIN, "You have reached level %d!", new_exp); } const bool manual_stat_level = new_exp % 3 == 0; // 3,6,9,12... // Must do this before actually changing experience_level, // so we will re-prompt on load if a hup is received. if (manual_stat_level && !skip_attribute_increase) if (!attribute_increase()) return; // abort level gain, the xp is still there // Set this after printing, since a more() might clear it. you.redraw_experience = true; crawl_state.stat_gain_prompt = false; you.experience_level = new_exp; you.max_level = you.experience_level; #ifdef USE_TILE_LOCAL // In case of intrinsic ability changes. tiles.layout_statcol(); redraw_screen(); #endif if (!skip_attribute_increase) species_stat_gain(you.species); switch (you.species) { case SP_VAMPIRE: if (you.experience_level == 3) { if (you.vampire_alive) { mprf(MSGCH_INTRINSIC_GAIN, "If you were bloodless " "you could now transform into a vampire bat."); } else { mprf(MSGCH_INTRINSIC_GAIN, "You can now transform into a vampire bat."); } } break; case SP_NAGA: if (!(you.experience_level % 3)) { mprf(MSGCH_INTRINSIC_GAIN, "Your skin feels tougher."); you.redraw_armour_class = true; } break; case SP_BASE_DRACONIAN: if (you.experience_level >= 7) { you.species = random_draconian_colour(); // We just changed our aptitudes, so some skills may now // be at the wrong level (with negative progress); if we // print anything in this condition, we might trigger a // --More--, a redraw, and a crash (#6376 on Mantis). // // Hence we first fix up our skill levels silently (passing // do_level_up = false) but save the old values; then when // we want the messages later, we restore the old skill // levels and call check_skill_level_change() again, this // time passing do_level_up = true. uint8_t saved_skills[NUM_SKILLS]; for (skill_type sk = SK_FIRST_SKILL; sk < NUM_SKILLS; ++sk) { saved_skills[sk] = you.skills[sk]; check_skill_level_change(sk, false); } // The player symbol depends on species. update_player_symbol(); #ifdef USE_TILE init_player_doll(); #endif mprf(MSGCH_INTRINSIC_GAIN, "Your scales start taking on %s colour.", article_a(scale_type(you.species)).c_str()); // Produce messages about skill increases/decreases. We // restore one skill level at a time so that at most the // skill being checked is at the wrong level. for (skill_type sk = SK_FIRST_SKILL; sk < NUM_SKILLS; ++sk) { const int oldapt = species_apt(sk, SP_BASE_DRACONIAN); const int newapt = species_apt(sk, you.species); if (oldapt != newapt) { mprf(MSGCH_INTRINSIC_GAIN, "You learn %s %s%s.", skill_name(sk), abs(oldapt - newapt) > 1 ? "much " : "", oldapt > newapt ? "slower" : "quicker"); } you.skills[sk] = saved_skills[sk]; check_skill_level_change(sk); } // It's possible we passed a training target due to // skills being rescaled to new aptitudes. Thus, we must // check the training targets. check_training_targets(); // Tell the player about their new species for (auto &mut : fake_mutations(you.species, false)) mprf(MSGCH_INTRINSIC_GAIN, "%s", mut.c_str()); // needs to be done early here, so HP doesn't look rotted // when we redraw the screen _gain_and_note_hp_mp(); updated_maxhp = true; redraw_screen(); } break; case SP_DEMONSPAWN: { bool gave_message = false; int level = 0; mutation_type first_body_facet = NUM_MUTATIONS; for (const player::demon_trait trait : you.demonic_traits) { if (is_body_facet(trait.mutation)) { if (first_body_facet < NUM_MUTATIONS && trait.mutation != first_body_facet) { if (you.experience_level == level) { mprf(MSGCH_MUTATION, "You feel monstrous as " "your demonic heritage exerts itself."); mark_milestone("monstrous", "discovered their " "monstrous ancestry!"); } break; } if (first_body_facet == NUM_MUTATIONS) { first_body_facet = trait.mutation; level = trait.level_gained; } } } for (const player::demon_trait trait : you.demonic_traits) { if (trait.level_gained == you.experience_level) { if (!gave_message) { mprf(MSGCH_INTRINSIC_GAIN, "Your demonic ancestry asserts itself..."); gave_message = true; } perma_mutate(trait.mutation, 1, "demonic ancestry"); } } break; } case SP_FELID: _felid_extra_life(); break; default: break; } give_level_mutations(you.species, you.experience_level); } if (species_is_draconian(you.species) && !(you.experience_level % 3)) { mprf(MSGCH_INTRINSIC_GAIN, "Your scales feel tougher."); you.redraw_armour_class = true; } if (!updated_maxhp) _gain_and_note_hp_mp(); xom_is_stimulated(12); if (in_good_standing(GOD_HEPLIAKLQANA)) upgrade_hepliaklqana_ancestor(); learned_something_new(HINT_NEW_LEVEL); } while (you.experience >= exp_needed(you.max_level + 1)) { ASSERT(you.experience_level == you.get_max_xl()); ASSERT(you.max_level < 127); // marshalled as an 1-byte value you.max_level++; if (you.species == SP_FELID) _felid_extra_life(); } you.redraw_title = true; #ifdef DGL_WHEREIS whereis_record(); #endif // Hints mode arbitrarily ends at xp 7. if (crawl_state.game_is_hints() && you.experience_level >= 7) hints_finished(); } void adjust_level(int diff, bool just_xp) { ASSERT((uint64_t)you.experience <= (uint64_t)MAX_EXP_TOTAL); const int max_exp_level = you.get_max_xl(); if (you.experience_level + diff < 1) you.experience = 0; else if (you.experience_level + diff >= max_exp_level) { const unsigned needed = exp_needed(max_exp_level); // Level gain when already at max should never reduce player XP; // but level loss (diff < 0) should. if (diff < 0 || you.experience < needed) you.experience = needed; } else { while (diff < 0 && you.experience >= exp_needed(max_exp_level)) { // Having XP for level 53 and going back to 26 due to a single // card would mean your felid is not going to get any extra lives // in foreseable future. you.experience -= exp_needed(max_exp_level) - exp_needed(max_exp_level - 1); diff++; } int old_min = exp_needed(you.experience_level); int old_max = exp_needed(you.experience_level + 1); int new_min = exp_needed(you.experience_level + diff); int new_max = exp_needed(you.experience_level + 1 + diff); dprf("XP before: %d\n", you.experience); dprf("%4.2f of %d..%d to %d..%d", (you.experience - old_min) * 1.0 / (old_max - old_min), old_min, old_max, new_min, new_max); you.experience = ((int64_t)(new_max - new_min)) * (you.experience - old_min) / (old_max - old_min) + new_min; dprf("XP after: %d\n", you.experience); } ASSERT((uint64_t)you.experience <= (uint64_t)MAX_EXP_TOTAL); if (!just_xp) level_change(); } /** * Get the player's current stealth value. * * (Keep in mind, while tweaking this function: the order in which stealth * modifiers are applied is significant!) * * @return The player's current stealth value. */ int player_stealth() { ASSERT(!crawl_state.game_is_arena()); // Extreme stealthiness can be enforced by wizmode stealth setting. if (crawl_state.disables[DIS_MON_SIGHT]) return 1000; // berserking, "clumsy" (0-dex), sacrifice stealth. if (you.berserk() || you.duration[DUR_CLUMSY] || you.get_mutation_level(MUT_NO_STEALTH)) { return 0; } int stealth = you.dex() * 3; stealth += you.skill(SK_STEALTH, 15); if (you.confused()) stealth /= 3; const item_def *arm = you.slot_item(EQ_BODY_ARMOUR, false); const item_def *boots = you.slot_item(EQ_BOOTS, false); if (arm) { // [ds] New stealth penalty formula from rob: SP = 6 * (EP^2) // Now 2 * EP^2 / 3 after EP rescaling. const int evp = you.unadjusted_body_armour_penalty(); const int penalty = evp * evp * 2 / 3; stealth -= penalty; const int pips = armour_type_prop(arm->sub_type, ARMF_STEALTH); stealth += pips * STEALTH_PIP; } stealth += STEALTH_PIP * you.scan_artefacts(ARTP_STEALTH); stealth += STEALTH_PIP * you.wearing(EQ_RINGS, RING_STEALTH); stealth -= STEALTH_PIP * you.wearing(EQ_RINGS, RING_ATTENTION); if (you.duration[DUR_STEALTH]) stealth += STEALTH_PIP * 2; if (you.form == transformation::blade_hands && you.species == SP_FELID && !you.airborne()) { stealth -= STEALTH_PIP; // klack klack klack go the blade paws // this is an absurd special case but also it's really funny so w/e } // Mutations. stealth += STEALTH_PIP * you.get_mutation_level(MUT_NIGHTSTALKER); stealth += (STEALTH_PIP / 2) * you.get_mutation_level(MUT_THIN_SKELETAL_STRUCTURE); stealth += STEALTH_PIP * you.get_mutation_level(MUT_CAMOUFLAGE); const int how_transparent = you.get_mutation_level(MUT_TRANSLUCENT_SKIN); if (how_transparent) stealth += 15 * (how_transparent); // Radiating silence is the negative complement of shouting all the // time... a sudden change from background noise to no noise is going // to clue anything in to the fact that something is very wrong... // a personal silence spell would naturally be different, but this // silence radiates for a distance and prevents monster spellcasting, // which pretty much gives away the stealth game. if (you.duration[DUR_SILENCE]) stealth -= STEALTH_PIP; // Bloodless vampires are stealthier. if (you.species == SP_VAMPIRE && !you.vampire_alive) stealth += STEALTH_PIP * 2; if (!you.airborne()) { if (you.in_water()) { // Merfolk can sneak up on monsters underwater -- bwr if (you.fishtail || you.species == SP_OCTOPODE) stealth += STEALTH_PIP; else if (!you.can_swim() && !you.extra_balanced()) stealth /= 2; // splashy-splashy } else if (boots && get_armour_ego_type(*boots) == SPARM_STEALTH) stealth += STEALTH_PIP; else if (you.has_usable_hooves()) stealth -= 5 + 5 * you.get_mutation_level(MUT_HOOVES); else if (you.species == SP_FELID && (you.form == transformation::none || you.form == transformation::appendage)) { stealth += 20; // paws } } // If you've been tagged with Corona or are Glowing, the glow // makes you extremely unstealthy. if (you.backlit()) stealth = stealth * 2 / 5; // On the other hand, shrouding has the reverse effect, if you know // how to make use of it: if (you.umbra()) { int umbra_mul = 1, umbra_div = 1; if (you.nightvision()) { umbra_mul = you.piety + MAX_PIETY; umbra_div = MAX_PIETY; } if (player_equip_unrand(UNRAND_SHADOWS) && 2 * umbra_mul < 3 * umbra_div) { umbra_mul = 3; umbra_div = 2; } stealth *= umbra_mul; stealth /= umbra_div; } if (you.form == transformation::shadow) stealth *= 2; // If you're surrounded by a storm, you're inherently pretty conspicuous. if (have_passive(passive_t::storm_shield)) { stealth = stealth * (MAX_PIETY - min((int)you.piety, piety_breakpoint(5))) / (MAX_PIETY - piety_breakpoint(0)); } // The shifting glow from the Orb, while too unstable to negate invis // or affect to-hit, affects stealth even more than regular glow. if (player_has_orb()) stealth /= 3; stealth = max(0, stealth); return stealth; } // Is a given duration about to expire? bool dur_expiring(duration_type dur) { const int value = you.duration[dur]; if (value <= 0) return false; return value <= duration_expire_point(dur); } static void _display_char_status(int value, const char *fmt, ...) { va_list argp; va_start(argp, fmt); string msg = vmake_stringf(fmt, argp); if (you.wizard) mprf("%s (%d).", msg.c_str(), value); else mprf("%s.", msg.c_str()); va_end(argp); } static void _display_vampire_status() { string msg = "At your current blood state you "; vector<const char *> attrib; if (!you.vampire_alive) { attrib.push_back("are immune to poison"); attrib.push_back("significantly resist cold"); attrib.push_back("are immune to negative energy"); attrib.push_back("resist torment"); attrib.push_back("do not heal with monsters in sight."); } else attrib.push_back("heal quickly."); if (!attrib.empty()) { msg += comma_separated_line(attrib.begin(), attrib.end()); mpr(msg); } } static void _display_movement_speed() { const int move_cost = (player_speed() * player_movement_speed()) / 10; const bool water = you.in_liquid(); const bool swim = you.swimming(); const bool fly = you.airborne(); const bool swift = (you.duration[DUR_SWIFTNESS] > 0 && you.attribute[ATTR_SWIFTNESS] >= 0); const bool antiswift = (you.duration[DUR_SWIFTNESS] > 0 && you.attribute[ATTR_SWIFTNESS] < 0); _display_char_status(move_cost, "Your %s speed is %s%s%s", // order is important for these: (swim) ? "swimming" : (water) ? "wading" : (fly) ? "flying" : "movement", (!water && swift) ? "aided by the wind" : (!water && antiswift) ? "hindered by the wind" : "", (!water && swift) ? ((move_cost >= 10) ? ", but still " : " and ") : (!water && antiswift) ? ((move_cost <= 10) ? ", but still " : " and ") : "", (move_cost < 8) ? "very quick" : (move_cost < 10) ? "quick" : (move_cost == 10) ? "average" : (move_cost < 13) ? "slow" : "very slow"); } static void _display_tohit() { #ifdef DEBUG_DIAGNOSTICS melee_attack attk(&you, nullptr); const int to_hit = attk.calc_to_hit(false); dprf("To-hit: %d", to_hit); #endif } static const char* _attack_delay_desc(int attack_delay) { return (attack_delay >= 200) ? "extremely slow" : (attack_delay >= 155) ? "very slow" : (attack_delay >= 125) ? "quite slow" : (attack_delay >= 105) ? "below average" : (attack_delay >= 95) ? "average" : (attack_delay >= 75) ? "above average" : (attack_delay >= 55) ? "quite fast" : (attack_delay >= 45) ? "very fast" : (attack_delay >= 35) ? "extremely fast" : "blindingly fast"; } /** * Print a message indicating the player's attack delay with their current * weapon & its ammo (if applicable). * * Assumes the attack speed of a ranged weapon does not depend on what * ammunition is being used (as long as it is valid). */ static void _display_attack_delay() { const item_def* weapon = you.weapon(); int delay; if (weapon && is_range_weapon(*weapon)) { item_def ammo; ammo.base_type = OBJ_MISSILES; ammo.sub_type = fires_ammo_type(*weapon); delay = you.attack_delay(&ammo, false).expected(); } else delay = you.attack_delay(nullptr, false).expected(); const bool at_min_delay = weapon && you.skill(item_attack_skill(*weapon)) >= weapon_min_delay_skill(*weapon); // Scale to fit the displayed weapon base delay, i.e., // normal speed is 100 (as in 100%). int avg = 10 * delay; _display_char_status(avg, "Your attack speed is %s%s%s", _attack_delay_desc(avg), at_min_delay ? " (and cannot be improved with additional weapon skill)" : "", you.adjusted_shield_penalty() ? " (and is slowed by your insufficient shield skill)" : ""); } // forward declaration static string _constriction_description(); void display_char_status() { const int halo_size = you.halo_radius(); if (halo_size >= 0) { if (halo_size > 37) mpr("You are illuminated by a large divine halo."); else if (halo_size > 10) mpr("You are illuminated by a divine halo."); else mpr("You are illuminated by a small divine halo."); } else if (you.haloed()) mpr("An external divine halo illuminates you."); if (you.species == SP_VAMPIRE) _display_vampire_status(); status_info inf; for (unsigned i = 0; i <= STATUS_LAST_STATUS; ++i) { if (fill_status_info(i, inf) && !inf.long_text.empty()) mpr(inf.long_text); } string cinfo = _constriction_description(); if (!cinfo.empty()) mpr(cinfo); _display_movement_speed(); _display_tohit(); _display_attack_delay(); // Display base attributes, if necessary. if (innate_stat(STAT_STR) != you.strength() || innate_stat(STAT_INT) != you.intel() || innate_stat(STAT_DEX) != you.dex()) { mprf("Your base attributes are Str %d, Int %d, Dex %d.", innate_stat(STAT_STR), innate_stat(STAT_INT), innate_stat(STAT_DEX)); } } bool player::clarity(bool calc_unid, bool items) const { if (you.get_mutation_level(MUT_CLARITY)) return true; if (have_passive(passive_t::clarity)) return true; return actor::clarity(calc_unid, items); } bool player::gourmand(bool calc_unid, bool items) const { return you.get_mutation_level(MUT_GOURMAND) > 0 || actor::gourmand(calc_unid, items); } bool player::stasis() const { return species == SP_FORMICID; } bool player::cloud_immune(bool calc_unid, bool items) const { return have_passive(passive_t::cloud_immunity) || actor::cloud_immune(calc_unid, items); } unsigned int exp_needed(int lev, int exp_apt) { unsigned int level = 0; // Note: For historical reasons, all of the following numbers are for a // species (like human) with XP aptitude 1, not 0 as one might expect. // Basic plan: // Section 1: levels 1- 5, second derivative goes 10-10-20-30. // Section 2: levels 6-13, second derivative is exponential/doubling. // Section 3: levels 14-27, second derivative is constant at 8470. // Here's a table: // // level xp delta delta2 // ===== ======= ===== ====== // 1 0 0 0 // 2 10 10 10 // 3 30 20 10 // 4 70 40 20 // 5 140 70 30 // 6 270 130 60 // 7 520 250 120 // 8 1010 490 240 // 9 1980 970 480 // 10 3910 1930 960 // 11 7760 3850 1920 // 12 15450 7690 3840 // 13 26895 11445 3755 // 14 45585 18690 7245 // 15 72745 27160 8470 // 16 108375 35630 8470 // 17 152475 44100 8470 // 18 205045 52570 8470 // 19 266085 61040 8470 // 20 335595 69510 8470 // 21 413575 77980 8470 // 22 500025 86450 8470 // 23 594945 94920 8470 // 24 698335 103390 8470 // 25 810195 111860 8470 // 26 930525 120330 8470 // 27 1059325 128800 8470 switch (lev) { case 1: level = 1; break; case 2: level = 10; break; case 3: level = 30; break; case 4: level = 70; break; default: if (lev < 13) { lev -= 4; level = 10 + 10 * lev + (60 << lev); } else { lev -= 12; level = 16675 + 5985 * lev + 4235 * lev * lev; } break; } if (exp_apt == -99) exp_apt = species_exp_modifier(you.species); return (unsigned int) ((level - 1) * apt_to_factor(exp_apt - 1)); } // returns bonuses from rings of slaying, etc. int slaying_bonus(bool ranged) { int ret = 0; ret += you.wearing(EQ_RINGS_PLUS, RING_SLAYING); ret += you.scan_artefacts(ARTP_SLAYING); if (you.wearing_ego(EQ_GLOVES, SPARM_ARCHERY) && ranged) ret += 4; ret += 3 * augmentation_amount(); if (you.duration[DUR_SONG_OF_SLAYING]) ret += you.props[SONG_OF_SLAYING_KEY].get_int(); if (you.duration[DUR_HORROR]) ret -= you.props[HORROR_PENALTY_KEY].get_int(); ret += you.attribute[ATTR_HEAVENLY_STORM]; return ret; } // Checks each equip slot for a randart, and adds up all of those with // a given property. Slow if any randarts are worn, so avoid where // possible. If `matches' is non-nullptr, items with nonzero property are // pushed onto *matches. int player::scan_artefacts(artefact_prop_type which_property, bool calc_unid, vector<const item_def *> *matches) const { int retval = 0; for (int i = EQ_FIRST_EQUIP; i < NUM_EQUIP; ++i) { if (melded[i] || equip[i] == -1) continue; const int eq = equip[i]; const item_def &item = inv[eq]; // Only weapons give their effects when in our hands. if (i == EQ_WEAPON && item.base_type != OBJ_WEAPONS) continue; int val = 0; // TODO: id check not needed, probably, due to full wear-id? if (is_artefact(item) && (calc_unid || fully_identified(item))) val = artefact_property(item, which_property); retval += val; if (matches && val) matches->push_back(&item); } return retval; } void dec_hp(int hp_loss, bool fatal, const char *aux) { ASSERT(!crawl_state.game_is_arena()); if (!fatal && you.hp < 1) you.hp = 1; if (!fatal && hp_loss >= you.hp) hp_loss = you.hp - 1; if (hp_loss < 1) return; // If it's not fatal, use ouch() so that notes can be taken. If it IS // fatal, somebody else is doing the bookkeeping, and we don't want to mess // with that. if (!fatal && aux) ouch(hp_loss, KILLED_BY_SOMETHING, MID_NOBODY, aux); else you.hp -= hp_loss; you.redraw_hit_points = true; } void calc_mp() { you.max_magic_points = get_real_mp(true); you.magic_points = min(you.magic_points, you.max_magic_points); you.redraw_magic_points = true; } void flush_mp() { if (Options.magic_point_warning && you.magic_points < you.max_magic_points * Options.magic_point_warning / 100) { mprf(MSGCH_DANGER, "* * * LOW MAGIC WARNING * * *"); } take_note(Note(NOTE_MP_CHANGE, you.magic_points, you.max_magic_points)); you.redraw_magic_points = true; } void dec_mp(int mp_loss, bool silent) { ASSERT(!crawl_state.game_is_arena()); if (mp_loss < 1) return; you.magic_points -= mp_loss; you.magic_points = max(0, you.magic_points); if (!silent) flush_mp(); } bool enough_hp(int minimum, bool suppress_msg, bool abort_macros) { ASSERT(!crawl_state.game_is_arena()); if (you.duration[DUR_DEATHS_DOOR]) { if (!suppress_msg) mpr("You cannot pay life while functionally dead."); if (abort_macros) { crawl_state.cancel_cmd_again(); crawl_state.cancel_cmd_repeat(); } return false; } // We want to at least keep 1 HP. -- bwr if (you.hp < minimum + 1) { if (!suppress_msg) mpr("You don't have enough health at the moment."); if (abort_macros) { crawl_state.cancel_cmd_again(); crawl_state.cancel_cmd_repeat(); } return false; } return true; } bool enough_mp(int minimum, bool suppress_msg, bool abort_macros) { ASSERT(!crawl_state.game_is_arena()); if (you.magic_points < minimum) { if (!suppress_msg) { if (get_real_mp(true) < minimum) mpr("You don't have enough magic capacity."); else mpr("You don't have enough magic at the moment."); } if (abort_macros) { crawl_state.cancel_cmd_again(); crawl_state.cancel_cmd_repeat(); } return false; } return true; } static int _rest_trigger_level(int max) { return (max * Options.rest_wait_percent) / 100; } static bool _should_stop_resting(int cur, int max) { return cur == max || cur == _rest_trigger_level(max); } void inc_mp(int mp_gain, bool silent) { ASSERT(!crawl_state.game_is_arena()); if (mp_gain < 1 || you.magic_points >= you.max_magic_points) return; you.magic_points += mp_gain; if (you.magic_points > you.max_magic_points) you.magic_points = you.max_magic_points; if (!silent) { if (_should_stop_resting(you.magic_points, you.max_magic_points)) interrupt_activity(activity_interrupt::full_mp); you.redraw_magic_points = true; } } // Note that "max_too" refers to the base potential, the actual // resulting max value is subject to penalties, bonuses, and scalings. // To avoid message spam, don't take notes when HP increases. void inc_hp(int hp_gain) { ASSERT(!crawl_state.game_is_arena()); if (hp_gain < 1 || you.hp >= you.hp_max) return; you.hp += hp_gain; if (you.hp > you.hp_max) you.hp = you.hp_max; if (_should_stop_resting(you.hp, you.hp_max)) interrupt_activity(activity_interrupt::full_hp); you.redraw_hit_points = true; } void rot_hp(int hp_loss) { if (!player_rotted() && hp_loss > 0) you.redraw_magic_points = true; const int initial_rot = you.hp_max_adj_temp; you.hp_max_adj_temp -= hp_loss; // don't allow more rot than you have normal mhp you.hp_max_adj_temp = max(-(get_real_hp(false, false) - 1), you.hp_max_adj_temp); if (initial_rot == you.hp_max_adj_temp) return; calc_hp(); if (you.species != SP_GHOUL) xom_is_stimulated(hp_loss * 25); you.redraw_hit_points = true; } int unrot_hp(int hp_recovered) { int hp_balance = 0; if (hp_recovered > -you.hp_max_adj_temp) { hp_balance = hp_recovered + you.hp_max_adj_temp; you.hp_max_adj_temp = 0; } else you.hp_max_adj_temp += hp_recovered; calc_hp(); you.redraw_hit_points = true; if (!player_rotted()) you.redraw_magic_points = true; return hp_balance; } int player_rotted() { return -you.hp_max_adj_temp; } void rot_mp(int mp_loss) { you.mp_max_adj -= mp_loss; calc_mp(); you.redraw_magic_points = true; } void inc_max_hp(int hp_gain) { you.hp += hp_gain; you.hp_max_adj_perm += hp_gain; calc_hp(); take_note(Note(NOTE_MAXHP_CHANGE, you.hp_max)); you.redraw_hit_points = true; } void dec_max_hp(int hp_loss) { you.hp_max_adj_perm -= hp_loss; calc_hp(); take_note(Note(NOTE_MAXHP_CHANGE, you.hp_max)); you.redraw_hit_points = true; } void set_hp(int new_amount) { ASSERT(!crawl_state.game_is_arena()); you.hp = new_amount; if (you.hp > you.hp_max) you.hp = you.hp_max; // Must remain outside conditional, given code usage. {dlb} you.redraw_hit_points = true; } void set_mp(int new_amount) { ASSERT(!crawl_state.game_is_arena()); you.magic_points = new_amount; if (you.magic_points > you.max_magic_points) you.magic_points = you.max_magic_points; take_note(Note(NOTE_MP_CHANGE, you.magic_points, you.max_magic_points)); // Must remain outside conditional, given code usage. {dlb} you.redraw_magic_points = true; } /** * Get the player's max HP * @param trans Whether to include transformations, berserk, * items etc. * @param rotted Whether to include the effects of rotting. * @return The player's calculated max HP. */ int get_real_hp(bool trans, bool rotted) { int hitp; hitp = you.experience_level * 11 / 2 + 8; hitp += you.hp_max_adj_perm; // Important: we shouldn't add Heroism boosts here. hitp += you.experience_level * you.skill(SK_FIGHTING, 5, true) / 70 + (you.skill(SK_FIGHTING, 3, true) + 1) / 2; // Racial modifier. hitp *= 10 + species_hp_modifier(you.species); hitp /= 10; const bool hep_frail = have_passive(passive_t::frail) || player_under_penance(GOD_HEPLIAKLQANA); // Mutations that increase HP by a percentage hitp *= 100 + (you.get_mutation_level(MUT_ROBUST) * 10) + (you.attribute[ATTR_DIVINE_VIGOUR] * 5) + (you.get_mutation_level(MUT_RUGGED_BROWN_SCALES) ? you.get_mutation_level(MUT_RUGGED_BROWN_SCALES) * 2 + 1 : 0) - (you.get_mutation_level(MUT_FRAIL) * 10) - (hep_frail ? 10 : 0) - (!you.vampire_alive ? 20 : 0); hitp /= 100; if (rotted) hitp += you.hp_max_adj_temp; if (trans) hitp += you.scan_artefacts(ARTP_HP); // Being berserk makes you resistant to damage. I don't know why. if (trans && you.berserk()) hitp = hitp * 3 / 2; // Some transformations give you extra hp. if (trans) hitp = hitp * form_hp_mod() / 10; #if TAG_MAJOR_VERSION == 34 if (trans && player_equip_unrand(UNRAND_ETERNAL_TORMENT)) hitp = hitp * 4 / 5; #endif return max(1, hitp); } int get_real_mp(bool include_items) { const int scale = 100; int spellcasting = you.skill(SK_SPELLCASTING, 1 * scale, true); int scaled_xl = you.experience_level * scale; // the first 4 experience levels give an extra .5 mp up to your spellcasting // the last 4 give no mp int enp = min(23 * scale, scaled_xl); int spell_extra = spellcasting; // 100% int invoc_extra = you.skill(SK_INVOCATIONS, 1 * scale, true) / 2; // 50% int evoc_extra = you.skill(SK_EVOCATIONS, 1 * scale, true) / 2; // 50% int highest_skill = max(spell_extra, max(invoc_extra, evoc_extra)); enp += highest_skill + min(8 * scale, min(highest_skill, scaled_xl)) / 2; // Analogous to ROBUST/FRAIL enp *= 100 + (you.get_mutation_level(MUT_HIGH_MAGIC) * 10) + (you.attribute[ATTR_DIVINE_VIGOUR] * 5) - (you.get_mutation_level(MUT_LOW_MAGIC) * 10); enp /= 100 * scale; // enp = stepdown_value(enp, 9, 18, 45, 100) enp += species_mp_modifier(you.species); // This is our "rotted" base, applied after multipliers enp += you.mp_max_adj; // Now applied after scaling so that power items are more useful -- bwr if (include_items) { enp += 9 * you.wearing(EQ_RINGS, RING_MAGICAL_POWER); enp += you.scan_artefacts(ARTP_MAGICAL_POWER); } if (include_items && you.wearing_ego(EQ_WEAPON, SPWPN_ANTIMAGIC)) enp /= 3; enp = max(enp, 0); return enp; } bool player_regenerates_hp() { if (you.has_mutation(MUT_NO_REGENERATION)) return false; return true; } bool player_regenerates_mp() { // Don't let DD use guardian spirit for free HP, since their // damage shaving is enough. (due, dpeg) if (you.spirit_shield() && you.species == SP_DEEP_DWARF) return false; #if TAG_MAJOR_VERSION == 34 // Pakellas blocks MP regeneration. if (have_passive(passive_t::no_mp_regen) || player_under_penance(GOD_PAKELLAS)) return false; #endif return true; } int get_contamination_level() { const int glow = you.magic_contamination; if (glow > 60000) return glow / 20000 + 4; if (glow > 40000) return 6; if (glow > 25000) return 5; if (glow > 15000) return 4; if (glow > 5000) return 3; if (glow > 3500) // An indicator that using another contamination-causing return 2; // ability might risk causing yellow glow. if (glow > 0) return 1; return 0; } bool player_severe_contamination() { return get_contamination_level() >= SEVERE_CONTAM_LEVEL; } /** * Provide a description of the given contamination 'level'. * * @param cont A contamination 'tier', corresponding to a nonlinear * contamination value; generated by get_contamination_level(). * * @return A string describing the player when in the given contamination * level. */ string describe_contamination(int cont) { /// Mappings from contamination levels to descriptions. static const string contam_descriptions[] = { "", "You are very lightly contaminated with residual magic.", "You are lightly contaminated with residual magic.", "You are contaminated with residual magic.", "You are heavily infused with residual magic.", "You are practically glowing with residual magic!", "Your entire body has taken on an eerie glow!", "You are engulfed in a nimbus of crackling magics!", }; ASSERT(cont >= 0); return contam_descriptions[min((size_t) cont, ARRAYSZ(contam_descriptions) - 1)]; } // Controlled is true if the player actively did something to cause // contamination. void contaminate_player(int change, bool controlled, bool msg) { ASSERT(!crawl_state.game_is_arena()); int old_amount = you.magic_contamination; int old_level = get_contamination_level(); bool was_glowing = player_severe_contamination(); int new_level = 0; #if TAG_MAJOR_VERSION == 34 if (change > 0 && player_equip_unrand(UNRAND_ETHERIC_CAGE)) change *= 2; #endif you.magic_contamination = max(0, min(250000, you.magic_contamination + change)); new_level = get_contamination_level(); if (you.magic_contamination != old_amount) dprf("change: %d radiation: %d", change, you.magic_contamination); if (new_level > old_level) { if (msg) { mprf(player_severe_contamination() ? MSGCH_WARN : MSGCH_PLAIN, "%s", describe_contamination(new_level).c_str()); } if (player_severe_contamination()) xom_is_stimulated(new_level * 25); } else if (msg && new_level < old_level) { if (old_level == 1 && new_level == 0) mpr("Your magical contamination has completely faded away."); else if (player_severe_contamination() || was_glowing) { mprf(MSGCH_RECOVERY, "You feel less contaminated with magical energies."); } if (!player_severe_contamination() && was_glowing && you.invisible()) { mpr("You fade completely from view now that you are no longer " "glowing from magical contamination."); } } if (you.magic_contamination > 0) learned_something_new(HINT_GLOWING); // Zin doesn't like mutations or mutagenic radiation. if (you_worship(GOD_ZIN)) { // Whenever the glow status is first reached, give a warning message. if (!was_glowing && player_severe_contamination()) did_god_conduct(DID_CAUSE_GLOWING, 0, false); // If the player actively did something to increase glowing, // Zin is displeased. else if (controlled && change > 0 && was_glowing) did_god_conduct(DID_CAUSE_GLOWING, 1 + new_level, true); } } /** * Increase the player's confusion duration. * * @param amount The number of turns to increase confusion duration by. * @param quiet Whether to suppress messaging on success/failure. * @param force Whether to ignore resistance (used only for intentional * self-confusion, e.g. via ambrosia). * @return Whether confusion was successful. */ bool confuse_player(int amount, bool quiet, bool force) { ASSERT(!crawl_state.game_is_arena()); if (amount <= 0) return false; if (!force && you.clarity()) { if (!quiet) mpr("You feel momentarily confused."); return false; } if (!force && you.duration[DUR_DIVINE_STAMINA] > 0) { if (!quiet) mpr("Your divine stamina protects you from confusion!"); return false; } const int old_value = you.duration[DUR_CONF]; you.increase_duration(DUR_CONF, amount, 40); if (you.duration[DUR_CONF] > old_value) { you.check_awaken(500); if (!quiet) { mprf(MSGCH_WARN, "You are %sconfused.", old_value > 0 ? "more " : ""); } learned_something_new(HINT_YOU_ENCHANTED); xom_is_stimulated((you.duration[DUR_CONF] - old_value) / BASELINE_DELAY); } return true; } void paralyse_player(string source, int amount) { if (!amount) amount = 2 + random2(6 + you.duration[DUR_PARALYSIS] / BASELINE_DELAY); you.paralyse(nullptr, amount, source); } bool poison_player(int amount, string source, string source_aux, bool force) { ASSERT(!crawl_state.game_is_arena()); if (crawl_state.disables[DIS_AFFLICTIONS]) return false; if (you.duration[DUR_DIVINE_STAMINA] > 0) { mpr("Your divine stamina protects you from poison!"); return false; } if (player_res_poison() >= 3) { dprf("Cannot poison, you are immune!"); return false; } else if (!force && player_res_poison() > 0 && !one_chance_in(3)) return false; const int old_value = you.duration[DUR_POISONING]; const bool was_fatal = poison_is_lethal(); if (player_res_poison() < 0) amount *= 2; you.duration[DUR_POISONING] += amount * 1000; if (you.duration[DUR_POISONING] > old_value) { if (poison_is_lethal() && !was_fatal) mprf(MSGCH_DANGER, "You are lethally poisoned!"); else { mprf(MSGCH_WARN, "You are %spoisoned.", old_value > 0 ? "more " : ""); } learned_something_new(HINT_YOU_POISON); } you.props["poisoner"] = source; you.props["poison_aux"] = source_aux; // Display the poisoned segment of our health, in case we take no damage you.redraw_hit_points = true; return amount; } int get_player_poisoning() { if (player_res_poison() < 3) { // Approximate the effect of damage shaving by giving the first // 25 points of poison damage for 'free' if (you.species == SP_DEEP_DWARF) return max(0, (you.duration[DUR_POISONING] / 1000) - 25); else return you.duration[DUR_POISONING] / 1000; } else return 0; } // The amount of aut needed for poison to end if // you.duration[DUR_POISONING] == dur, assuming no Chei/DD shenanigans. // This function gives the following behaviour: // * 1/15 of current poison is removed every 10 aut normally // * but speed of poison is capped between 0.025 and 1.000 HP/aut static double _poison_dur_to_aut(double dur) { // Poison already at minimum speed. if (dur < 15.0 * 250.0) return dur / 25.0; // Poison is not at maximum speed. if (dur < 15.0 * 10000.0) return 150.0 + 10.0 * log(dur / (15.0 * 250.0)) / log(15.0 / 14.0); return 150.0 + (dur - 15.0 * 10000.0) / 1000.0 + 10.0 * log(10000.0 / 250.0) / log(15.0 / 14.0); } // The inverse of the above function, i.e. the amount of poison needed // to last for aut time. static double _poison_aut_to_dur(double aut) { // Amount of time that poison lasts at minimum speed. if (aut < 150.0) return aut * 25.0; // Amount of time that poison exactly at the maximum speed lasts. const double aut_from_max_speed = 150.0 + 10.0 * log(40.0) / log(15.0 / 14.0); if (aut < aut_from_max_speed) return 15.0 * 250.0 * exp(log(15.0 / 14.0) / 10.0 * (aut - 150.0)); return 15.0 * 10000.0 + 1000.0 * (aut - aut_from_max_speed); } void handle_player_poison(int delay) { const double cur_dur = you.duration[DUR_POISONING]; const double cur_aut = _poison_dur_to_aut(cur_dur); // If Cheibriados has slowed your life processes, poison affects you less // quickly (you take the same total damage, but spread out over a longer // period of time). const double delay_scaling = have_passive(passive_t::slow_metabolism) ? 2.0 / 3.0 : 1.0; const double new_aut = cur_aut - ((double) delay) * delay_scaling; const double new_dur = _poison_aut_to_dur(new_aut); const int decrease = you.duration[DUR_POISONING] - (int) new_dur; // Transforming into a form with no metabolism merely suspends the poison // but doesn't let your body get rid of it. if (you.is_nonliving() || (you.undead_state() && !you.vampire_alive)) return; // Other sources of immunity (Zin, staff of Olgreb) let poison dissipate. bool do_dmg = (player_res_poison() >= 3 ? false : true); int dmg = (you.duration[DUR_POISONING] / 1000) - ((you.duration[DUR_POISONING] - decrease) / 1000); // Approximate old damage shaving by giving immunity to small amounts // of poison. Stronger poison will do the same damage as for non-DD // until it goes below the threshold, which is a bit weird, but // so is damage shaving. if (you.species == SP_DEEP_DWARF && you.duration[DUR_POISONING] - decrease < 25000) { dmg = (you.duration[DUR_POISONING] / 1000) - (25000 / 1000); if (dmg < 0) dmg = 0; } msg_channel_type channel = MSGCH_PLAIN; const char *adj = ""; if (dmg > 6) { channel = MSGCH_DANGER; adj = "extremely "; } else if (dmg > 2) { channel = MSGCH_WARN; adj = "very "; } if (do_dmg && dmg > 0) { int oldhp = you.hp; ouch(dmg, KILLED_BY_POISON); if (you.hp < oldhp) mprf(channel, "You feel %ssick.", adj); } // Now decrease the poison in our system reduce_player_poison(decrease); } void reduce_player_poison(int amount) { if (amount <= 0) return; you.duration[DUR_POISONING] -= amount; // Less than 1 point of damage remaining, so just end the poison if (you.duration[DUR_POISONING] < 1000) you.duration[DUR_POISONING] = 0; if (you.duration[DUR_POISONING] <= 0) { you.duration[DUR_POISONING] = 0; you.props.erase("poisoner"); you.props.erase("poison_aux"); mprf(MSGCH_RECOVERY, "You are no longer poisoned."); } you.redraw_hit_points = true; } // Takes *current* regeneration rate into account. Might sometimes be // incorrect, but hopefully if so then the player is surviving with 1 HP. bool poison_is_lethal() { if (you.hp <= 0) return get_player_poisoning(); if (get_player_poisoning() < you.hp) return false; return poison_survival() <= 0; } // Try to predict the minimum value of the player's health in the coming // turns given the current poison amount and regen rate. int poison_survival() { if (!get_player_poisoning()) return you.hp; const int rr = player_regen(); const bool chei = have_passive(passive_t::slow_metabolism); const bool dd = (you.species == SP_DEEP_DWARF); const int amount = you.duration[DUR_POISONING]; const double full_aut = _poison_dur_to_aut(amount); // Calculate the poison amount at which regen starts to beat poison. double min_poison_rate = 0.25; if (dd) min_poison_rate = 25.0/15.0; if (chei) min_poison_rate /= 1.5; int regen_beats_poison; if (rr <= (int) (100.0 * min_poison_rate)) regen_beats_poison = dd ? 25000 : 0; else { regen_beats_poison = 150 * rr; if (chei) regen_beats_poison = 3 * regen_beats_poison / 2; } if (rr == 0) return min(you.hp, you.hp - amount / 1000 + regen_beats_poison / 1000); // Calculate the amount of time until regen starts to beat poison. double poison_duration = full_aut - _poison_dur_to_aut(regen_beats_poison); if (poison_duration < 0) poison_duration = 0; if (chei) poison_duration *= 1.5; // Worst case scenario is right before natural regen gives you a point of // HP, so consider the nearest two such points. const int predicted_regen = (int) ((((double) you.hit_points_regeneration) + rr * poison_duration / 10.0) / 100.0); double test_aut1 = (100.0 * predicted_regen - 1.0 - ((double) you.hit_points_regeneration)) / (rr / 10.0); double test_aut2 = (100.0 * predicted_regen + 99.0 - ((double) you.hit_points_regeneration)) / (rr / 10.0); if (chei) { test_aut1 /= 1.5; test_aut2 /= 1.5; } const int test_amount1 = _poison_aut_to_dur(full_aut - test_aut1); const int test_amount2 = _poison_aut_to_dur(full_aut - test_aut2); int prediction1 = you.hp; int prediction2 = you.hp; // Don't look backwards in time. if (test_aut1 > 0) prediction1 -= (amount / 1000 - test_amount1 / 1000 - (predicted_regen - 1)); prediction2 -= (amount / 1000 - test_amount2 / 1000 - predicted_regen); return min(prediction1, prediction2); } bool miasma_player(actor *who, string source_aux) { ASSERT(!crawl_state.game_is_arena()); if (you.res_rotting() || you.duration[DUR_DEATHS_DOOR]) return false; if (you.duration[DUR_DIVINE_STAMINA] > 0) { mpr("Your divine stamina protects you from the miasma!"); return false; } bool success = poison_player(5 + roll_dice(3, 12), who ? who->name(DESC_A) : "", source_aux); if (coinflip()) { you.rot(who, 1); success = true; } if (one_chance_in(3)) { slow_player(10 + random2(5)); success = true; } return success; } bool napalm_player(int amount, string source, string source_aux) { ASSERT(!crawl_state.game_is_arena()); if (player_res_sticky_flame() || amount <= 0 || you.duration[DUR_WATER_HOLD] || feat_is_watery(grd(you.pos()))) return false; const int old_value = you.duration[DUR_LIQUID_FLAMES]; you.increase_duration(DUR_LIQUID_FLAMES, amount, 100); if (you.duration[DUR_LIQUID_FLAMES] > old_value) mprf(MSGCH_WARN, "You are covered in liquid flames!"); you.props["sticky_flame_source"] = source; you.props["sticky_flame_aux"] = source_aux; return true; } void dec_napalm_player(int delay) { delay = min(delay, you.duration[DUR_LIQUID_FLAMES]); if (feat_is_watery(grd(you.pos()))) { if (you.ground_level()) mprf(MSGCH_WARN, "The flames go out!"); else mprf(MSGCH_WARN, "You dip into the water, and the flames go out!"); you.duration[DUR_LIQUID_FLAMES] = 0; you.props.erase("sticky_flame_source"); you.props.erase("sticky_flame_aux"); return; } mprf(MSGCH_WARN, "You are covered in liquid flames!"); const int hurted = resist_adjust_damage(&you, BEAM_FIRE, random2avg(9, 2) + 1); you.expose_to_element(BEAM_STICKY_FLAME, 2); maybe_melt_player_enchantments(BEAM_STICKY_FLAME, hurted * delay / BASELINE_DELAY); ouch(hurted * delay / BASELINE_DELAY, KILLED_BY_BURNING); you.duration[DUR_LIQUID_FLAMES] -= delay; if (you.duration[DUR_LIQUID_FLAMES] <= 0) { you.props.erase("sticky_flame_source"); you.props.erase("sticky_flame_aux"); } } bool slow_player(int turns) { ASSERT(!crawl_state.game_is_arena()); if (turns <= 0) return false; if (you.stasis()) { mpr("Your stasis prevents you from being slowed."); return false; } // Multiplying these values because moving while slowed takes longer than // the usual delay. turns = haste_mul(turns); int threshold = haste_mul(100); if (you.duration[DUR_SLOW] >= threshold * BASELINE_DELAY) mpr("You already are as slow as you could be."); else { if (you.duration[DUR_SLOW] == 0) mpr("You feel yourself slow down."); else mpr("You feel as though you will be slow longer."); you.increase_duration(DUR_SLOW, turns, threshold); learned_something_new(HINT_YOU_ENCHANTED); } return true; } void dec_slow_player(int delay) { if (!you.duration[DUR_SLOW]) return; if (you.duration[DUR_SLOW] > BASELINE_DELAY) { // Make slowing and hasting effects last as long. you.duration[DUR_SLOW] -= you.duration[DUR_HASTE] ? haste_mul(delay) : delay; } if (you.torpor_slowed()) { you.duration[DUR_SLOW] = 1; return; } if (you.props.exists(TORPOR_SLOWED_KEY)) you.props.erase(TORPOR_SLOWED_KEY); if (you.duration[DUR_SLOW] <= BASELINE_DELAY) { you.duration[DUR_SLOW] = 0; if (!have_stat_zero()) mprf(MSGCH_DURATION, "You feel yourself speed up."); } } void dec_berserk_recovery_player(int delay) { if (!you.duration[DUR_BERSERK_COOLDOWN]) return; if (you.duration[DUR_BERSERK_COOLDOWN] > BASELINE_DELAY) { you.duration[DUR_BERSERK_COOLDOWN] -= you.duration[DUR_HASTE] ? haste_mul(delay) : delay; } if (you.duration[DUR_BERSERK_COOLDOWN] <= BASELINE_DELAY) { mprf(MSGCH_DURATION, "You recover from your berserk rage."); you.duration[DUR_BERSERK_COOLDOWN] = 0; } } bool haste_player(int turns, bool rageext) { ASSERT(!crawl_state.game_is_arena()); if (turns <= 0) return false; if (you.stasis()) { mpr("Your stasis prevents you from being hasted."); return false; } // Cutting the nominal turns in half since hasted actions take half the // usual delay. turns = haste_div(turns); const int threshold = 40; if (!you.duration[DUR_HASTE]) mpr("You feel yourself speed up."); else if (you.duration[DUR_HASTE] > threshold * BASELINE_DELAY) mpr("You already have as much speed as you can handle."); else if (!rageext) mpr("You feel as though your hastened speed will last longer."); you.increase_duration(DUR_HASTE, turns, threshold); return true; } void dec_haste_player(int delay) { if (!you.duration[DUR_HASTE]) return; if (you.duration[DUR_HASTE] > BASELINE_DELAY) { int old_dur = you.duration[DUR_HASTE]; you.duration[DUR_HASTE] -= delay; int threshold = 6 * BASELINE_DELAY; // message if we cross the threshold if (old_dur > threshold && you.duration[DUR_HASTE] <= threshold) { mprf(MSGCH_DURATION, "Your extra speed is starting to run out."); if (coinflip()) you.duration[DUR_HASTE] -= BASELINE_DELAY; } } else if (you.duration[DUR_HASTE] <= BASELINE_DELAY) { if (!you.duration[DUR_BERSERK]) mprf(MSGCH_DURATION, "You feel yourself slow down."); you.duration[DUR_HASTE] = 0; } } void dec_disease_player(int delay) { if (you.disease) { int rr = 50; // Extra regeneration means faster recovery from disease. // But not if not actually regenerating! if (player_regenerates_hp()) rr += _player_bonus_regen(); // Trog's Hand. if (you.duration[DUR_TROGS_HAND]) rr += 100; rr = div_rand_round(rr * delay, 50); you.disease -= rr; if (you.disease < 0) you.disease = 0; if (you.disease == 0) mprf(MSGCH_RECOVERY, "You feel your health improve."); } } static void _dec_elixir_hp(int delay) { you.duration[DUR_ELIXIR_HEALTH] -= delay; if (you.duration[DUR_ELIXIR_HEALTH] < 0) you.duration[DUR_ELIXIR_HEALTH] = 0; int heal = (delay * you.hp_max / 10) / BASELINE_DELAY; if (!you.duration[DUR_DEATHS_DOOR]) inc_hp(heal); } static void _dec_elixir_mp(int delay) { you.duration[DUR_ELIXIR_MAGIC] -= delay; if (you.duration[DUR_ELIXIR_MAGIC] < 0) you.duration[DUR_ELIXIR_MAGIC] = 0; int heal = (delay * you.max_magic_points / 10) / BASELINE_DELAY; inc_mp(heal); } void dec_elixir_player(int delay) { if (you.duration[DUR_ELIXIR_HEALTH]) _dec_elixir_hp(delay); if (you.duration[DUR_ELIXIR_MAGIC]) _dec_elixir_mp(delay); } void dec_ambrosia_player(int delay) { if (!you.duration[DUR_AMBROSIA]) return; // ambrosia ends when confusion does. if (!you.confused()) you.duration[DUR_AMBROSIA] = 0; you.duration[DUR_AMBROSIA] = max(0, you.duration[DUR_AMBROSIA] - delay); // 3-5 per turn, 9-50 over (3-10) turns const int hp_restoration = div_rand_round(delay*(3 + random2(3)), BASELINE_DELAY); const int mp_restoration = div_rand_round(delay*(3 + random2(3)), BASELINE_DELAY); if (!you.duration[DUR_DEATHS_DOOR]) inc_hp(you.scale_potion_healing(hp_restoration)); inc_mp(mp_restoration); if (!you.duration[DUR_AMBROSIA]) mpr("You feel less invigorated."); } void dec_channel_player(int delay) { if (!you.duration[DUR_CHANNEL_ENERGY]) return; you.duration[DUR_CHANNEL_ENERGY] = max(0, you.duration[DUR_CHANNEL_ENERGY] - delay); // 3-5 per turn, 9-50 over (3-10) turns const int mp_restoration = div_rand_round(delay*(3 + random2(3)), BASELINE_DELAY); inc_mp(mp_restoration); if (!you.duration[DUR_CHANNEL_ENERGY]) mpr("You feel less invigorated."); } void dec_frozen_ramparts(int delay) { if (!you.duration[DUR_FROZEN_RAMPARTS]) return; you.duration[DUR_FROZEN_RAMPARTS] = max(0, you.duration[DUR_FROZEN_RAMPARTS] - delay); if (!you.duration[DUR_FROZEN_RAMPARTS]) { ASSERT(you.props.exists(FROZEN_RAMPARTS_KEY)); const auto &pos = you.props[FROZEN_RAMPARTS_KEY].get_coord(); ASSERT(in_bounds(pos)); for (distance_iterator di(pos, false, false, spell_range(SPELL_FROZEN_RAMPARTS, -1, false)); di; di++) { env.pgrid(*di) &= ~FPROP_ICY; env.map_knowledge(*di).flags &= ~MAP_ICY; } you.props.erase(FROZEN_RAMPARTS_KEY); env.level_state &= ~LSTATE_ICY_WALL; mpr("The frozen ramparts melt away."); } } bool invis_allowed(bool quiet, string *fail_reason) { string msg; bool success = true; if (you.haloed() && you.halo_radius() != -1) { bool divine = you.attribute[ATTR_HEAVENLY_STORM] > 0 || you.religion == GOD_SHINING_ONE; bool weapon = player_equip_unrand(UNRAND_EOS); string reason; if (divine && weapon) reason = "Your weapon and divine halo glow too brightly"; else if (divine) reason = "Your divine halo glows too radiantly"; else if (weapon) reason = "Your weapon shines too brightly"; else die("haloed by an unknown source"); msg = reason + " to become invisible."; success = false; } else if (you.backlit()) { msg = "Invisibility will do you no good right now"; if (quiet) success = false; else if (!quiet && !yesno((msg + "; use anyway?").c_str(), false, 'n')) { canned_msg(MSG_OK); success = false; quiet = true; // since we just said something } msg += "."; } if (!success) { if (fail_reason) *fail_reason = msg; if (!quiet) mpr(msg); } return success; } bool flight_allowed(bool quiet, string *fail_reason) { string msg; bool success = true; if (get_form()->forbids_flight()) { msg = you.form == transformation::tree ? "Your roots keep you in place." : "You can't fly in this form."; success = false; } else if (you.liquefied_ground() && you.duration[DUR_LIQUEFYING] == 0) { msg = "You can't fly while stuck in liquid ground."; success = false; } if (!success) { if (fail_reason) *fail_reason = msg; if (!quiet) mpr(msg); } return success; } void float_player() { if (you.fishtail) { mpr("Your tail turns into legs as you fly out of the water."); merfolk_stop_swimming(); } else if (you.tengu_flight()) mpr("You swoop lightly up into the air."); else mpr("You fly up into the air."); if (you.species == SP_TENGU) you.redraw_evasion = true; } void fly_player(int pow, bool already_flying) { if (!flight_allowed()) return; bool standing = !you.airborne() && !already_flying; if (!already_flying) mprf(MSGCH_DURATION, "You feel %s buoyant.", standing ? "very" : "more"); you.increase_duration(DUR_FLIGHT, 25 + random2(pow), 100); if (standing) float_player(); } void enable_emergency_flight() { mprf("You can't survive in this terrain! You fly above the %s, but the " "process is draining.", (grd(you.pos()) == DNGN_LAVA) ? "lava" : (grd(you.pos()) == DNGN_DEEP_WATER) ? "water" : "buggy terrain"); you.props[EMERGENCY_FLIGHT_KEY] = true; } /** * Handle the player's flight ending. Apply emergency flight if needed. * * @param quiet Should we notify the player flight is ending? * @return If flight was ended. */ bool land_player(bool quiet) { // there was another source keeping you aloft if (you.airborne()) return false; // Handle landing on (formerly) instakill terrain if (is_feat_dangerous(grd(you.pos()))) { enable_emergency_flight(); return false; } if (!quiet) mpr("You float gracefully downwards."); if (you.species == SP_TENGU) you.redraw_evasion = true; you.attribute[ATTR_FLIGHT_UNCANCELLABLE] = 0; // Re-enter the terrain. move_player_to_grid(you.pos(), false); return true; } static void _end_water_hold() { you.duration[DUR_WATER_HOLD] = 0; you.props.erase("water_holder"); } bool player::clear_far_engulf() { if (!you.duration[DUR_WATER_HOLD]) return false; monster * const mons = monster_by_mid(you.props["water_holder"].get_int()); if (!mons || !mons->alive() || !adjacent(mons->pos(), you.pos())) { if (you.res_water_drowning()) mpr("The water engulfing you falls away."); else mpr("You gasp with relief as air once again reaches your lungs."); _end_water_hold(); return true; } return false; } void handle_player_drowning(int delay) { if (you.clear_far_engulf()) return; if (you.res_water_drowning()) { // Reset so damage doesn't ramp up while able to breathe you.duration[DUR_WATER_HOLD] = 10; } else { you.duration[DUR_WATER_HOLD] += delay; int dam = div_rand_round((28 + stepdown((float)you.duration[DUR_WATER_HOLD], 28.0)) * delay, BASELINE_DELAY * 10); ouch(dam, KILLED_BY_WATER, you.props["water_holder"].get_int()); mprf(MSGCH_WARN, "Your lungs strain for air!"); } } int count_worn_ego(int which_ego) { int result = 0; for (int slot = EQ_MIN_ARMOUR; slot <= EQ_MAX_ARMOUR; ++slot) { if (you.equip[slot] != -1 && !you.melded[slot] && get_armour_ego_type(you.inv[you.equip[slot]]) == which_ego) { result++; } } return result; } player::player() { // warning: this constructor is called for `you` in an indeterminate order // with respect to other globals, and so anything that depends on a global // you should not do here. This includes things like `branches`, as well as // any const static string prop name -- any object that needs to call a // constructor is risky, and may or may not have called it yet. E.g. strings // could be empty, branches could have every branch set as the dungeon, etc. // One candidate location is startup.cc:_initialize, which is nearly the // first things called in the launch game loop. chr_god_name.clear(); chr_species_name.clear(); chr_class_name.clear(); // Permanent data: your_name.clear(); species = SP_UNKNOWN; char_class = JOB_UNKNOWN; type = MONS_PLAYER; mid = MID_PLAYER; position.reset(); #ifdef WIZARD wizard = Options.wiz_mode == WIZ_YES; explore = Options.explore_mode == WIZ_YES; #else wizard = false; explore = false; #endif suppress_wizard = false; birth_time = time(0); // Long-term state: elapsed_time = 0; elapsed_time_at_last_input = 0; hp = 0; hp_max = 0; hp_max_adj_temp = 0; hp_max_adj_perm = 0; magic_points = 0; max_magic_points = 0; mp_max_adj = 0; stat_loss.init(0); base_stats.init(0); hunger = HUNGER_DEFAULT; hunger_state = HS_SATIATED; disease = 0; max_level = 1; hit_points_regeneration = 0; magic_points_regeneration = 0; experience = 0; total_experience = 0; experience_level = 1; gold = 0; zigs_completed = 0; zig_max = 0; equip.init(-1); melded.reset(); unrand_reacts.reset(); last_unequip = -1; symbol = MONS_PLAYER; form = transformation::none; for (auto &item : inv) item.clear(); runes.reset(); obtainable_runes = 15; spell_library.reset(); spells.init(SPELL_NO_SPELL); old_vehumet_gifts.clear(); spell_no = 0; vehumet_gifts.clear(); chapter = CHAPTER_ORB_HUNTING; royal_jelly_dead = false; transform_uncancellable = false; fishtail = false; vampire_alive = true; pet_target = MHITNOT; duration.init(0); apply_berserk_penalty = false; berserk_penalty = 0; attribute.init(0); // Default to flying the first time you wear boots of flying. attribute[ATTR_LAST_FLIGHT_STATUS] = 1; quiver.init(ENDOFPACK); last_timer_effect.init(0); next_timer_effect.init(20 * BASELINE_DELAY); pending_revival = false; lives = 0; deaths = 0; xray_vision = false; init_skills(); skill_menu_do = SKM_NONE; skill_menu_view = SKM_NONE; transfer_from_skill = SK_NONE; transfer_to_skill = SK_NONE; transfer_skill_points = 0; transfer_total_skill_points = 0; skill_cost_level = 1; exp_available = 0; item_description.init(255); unique_items.init(UNIQ_NOT_EXISTS); unique_creatures.reset(); force_autopickup.init(0); kills = KillMaster(); where_are_you = BRANCH_DUNGEON; depth = 1; branch_stairs.init(0); religion = GOD_NO_GOD; jiyva_second_name.clear(); piety = 0; piety_hysteresis = 0; gift_timeout = 0; saved_good_god_piety = 0; previous_good_god = GOD_NO_GOD; penance.init(0); worshipped.init(0); num_current_gifts.init(0); num_total_gifts.init(0); one_time_ability_used.reset(); piety_max.init(0); exp_docked.init(0); exp_docked_total.init(0); mutation.init(0); innate_mutation.init(0); temp_mutation.init(0); demonic_traits.clear(); sacrifices.init(0); magic_contamination = 0; seen_weapon.init(0); seen_armour.init(0); seen_misc.reset(); octopus_king_rings = 0x00; normal_vision = LOS_DEFAULT_RANGE; current_vision = LOS_DEFAULT_RANGE; real_time_ms = chrono::milliseconds::zero(); real_time_delta = chrono::milliseconds::zero(); num_turns = 0; exploration = 0; trapped = false; last_view_update = 0; spell_letter_table.init(-1); ability_letter_table.init(ABIL_NON_ABILITY); uniq_map_tags.clear(); uniq_map_names.clear(); uniq_map_tags_abyss.clear(); uniq_map_names_abyss.clear(); vault_list.clear(); global_info = PlaceInfo(); global_info.assert_validity(); m_quiver = player_quiver(); props.clear(); beholders.clear(); fearmongers.clear(); dactions.clear(); level_stack.clear(); type_ids.init(false); banished_by.clear(); banished_power = 0; last_mid = 0; last_cast_spell = SPELL_NO_SPELL; // Non-saved UI state: prev_targ = MHITNOT; prev_grd_targ.reset(); divine_exegesis = false; travel_x = 0; travel_y = 0; travel_z = level_id(); running.clear(); travel_ally_pace = false; received_weapon_warning = false; received_noskill_warning = false; wizmode_teleported_into_rock = false; ash_init_bondage(this); digging = false; delay_queue.clear(); last_keypress_time = chrono::system_clock::now(); action_count.clear(); branches_left.reset(); // Volatile (same-turn) state: turn_is_over = false; banished = false; wield_change = false; redraw_quiver = false; redraw_status_lights = false; redraw_hit_points = false; redraw_magic_points = false; redraw_stats.init(false); redraw_experience = false; redraw_armour_class = false; redraw_evasion = false; redraw_title = false; flash_colour = BLACK; flash_where = nullptr; time_taken = 0; shield_blocks = 0; abyss_speed = 0; game_seed = 0; fully_seeded = true; deterministic_levelgen = true; old_hunger = hunger; los_noise_level = 0; ///< temporary slot for loud noise levels los_noise_last_turn = 0; ///< loudest noise heard on the last turn, for HUD display transit_stair = DNGN_UNSEEN; entering_level = false; reset_escaped_death(); on_current_level = true; seen_portals = 0; frame_no = 0; save = nullptr; prev_save_version.clear(); clear_constricted(); constricting = 0; // Protected fields: clear_place_info(); } void player::init_skills() { auto_training = !(Options.default_manual_training); skills.init(0); train.init(TRAINING_DISABLED); train_alt.init(TRAINING_DISABLED); training.init(0); can_currently_train.reset(); skill_points.init(0); ct_skill_points.init(0); skill_order.init(MAX_SKILL_ORDER); training_targets.init(0); exercises.clear(); exercises_all.clear(); } player_save_info& player_save_info::operator=(const player& rhs) { name = rhs.your_name; experience = rhs.experience; experience_level = rhs.experience_level; wizard = rhs.wizard || rhs.suppress_wizard; species = rhs.species; species_name = rhs.chr_species_name; class_name = rhs.chr_class_name; religion = rhs.religion; god_name = rhs.chr_god_name; jiyva_second_name= rhs.jiyva_second_name; // [ds] Perhaps we should move game type to player? saved_game_type = crawl_state.type; return *this; } bool player_save_info::operator<(const player_save_info& rhs) const { return experience_level > rhs.experience_level || (experience_level == rhs.experience_level && name < rhs.name); } string player_save_info::really_short_desc() const { ostringstream desc; desc << name << " the " << species_name << ' ' << class_name; return desc.str(); } string player_save_info::short_desc() const { ostringstream desc; const string qualifier = game_state::game_type_name_for(saved_game_type); if (!qualifier.empty()) desc << "[" << qualifier << "] "; desc << name << ", a level " << experience_level << ' ' << species_name << ' ' << class_name; if (religion == GOD_JIYVA) desc << " of " << god_name << " " << jiyva_second_name; else if (religion != GOD_NO_GOD) desc << " of " << god_name; #ifdef WIZARD if (wizard) desc << " (WIZ)"; #endif return desc.str(); } player::~player() { if (CrawlIsCrashing && save) { save->abort(); delete save; save = nullptr; } ASSERT(!save); // the save file should be closed or deleted } bool player::airborne() const { // Might otherwise be airborne, but currently stuck to the ground if (get_form()->forbids_flight()) return false; if (duration[DUR_FLIGHT] || you.props[EMERGENCY_FLIGHT_KEY].get_bool() || attribute[ATTR_PERM_FLIGHT] || get_form()->enables_flight()) { return true; } return false; } bool player::is_banished() const { return banished; } bool player::is_sufficiently_rested() const { // Only return false if resting will actually help. return (!player_regenerates_hp() || hp >= _rest_trigger_level(hp_max)) && (magic_points >= _rest_trigger_level(max_magic_points) || !player_regenerates_mp()); } bool player::in_water() const { return ground_level() && !you.can_water_walk() && feat_is_water(grd(pos())); } bool player::in_liquid() const { return in_water() || liquefied_ground(); } bool player::can_swim(bool permanently) const { // Transforming could be fatal if it would cause unequipment of // stat-boosting boots or heavy armour. return (species_can_swim(species) || body_size(PSIZE_BODY) >= SIZE_GIANT || !permanently) && form_can_swim(); } /// Can the player do a passing imitation of a notorious Palestinian? bool player::can_water_walk() const { return have_passive(passive_t::water_walk) || you.props.exists(TEMP_WATERWALK_KEY); } int player::visible_igrd(const coord_def &where) const { if (grd(where) == DNGN_LAVA || (grd(where) == DNGN_DEEP_WATER && !species_likes_water(species))) { return NON_ITEM; } return igrd(where); } bool player::has_spell(spell_type spell) const { return find(begin(spells), end(spells), spell) != end(spells); } bool player::cannot_speak() const { if (silenced(pos())) return true; if (cannot_move()) // we allow talking during sleep ;) return true; // No transform that prevents the player from speaking yet. // ... yet setting this would prevent saccing junk and similar activities // for no good reason. return false; } static const string shout_verbs[] = {"shout", "yell", "scream"}; static const string felid_shout_verbs[] = {"meow", "yowl", "caterwaul"}; static const string frog_shout_verbs[] = {"ribbit", "croak", "bellow"}; static const string dog_shout_verbs[] = {"bark", "howl", "screech"}; /** * What verb should be used to describe the player's shouting? * * @param directed Whether you're shouting at anyone in particular. * @return A shouty kind of verb. */ string player::shout_verb(bool directed) const { if (!get_form()->shout_verb.empty()) return get_form()->shout_verb; const int screaminess = max(get_mutation_level(MUT_SCREAM) - 1, 0); if (species == SP_GNOLL) return dog_shout_verbs[screaminess]; if (species == SP_BARACHI) return frog_shout_verbs[screaminess]; if (species != SP_FELID) return shout_verbs[screaminess]; if (directed && screaminess == 0) return "hiss"; // hiss at, not meow at return felid_shout_verbs[screaminess]; } /** * How loud are the player's shouts? * * @return The noise produced by a single player shout. */ int player::shout_volume() const { const int base_noise = 12 + get_form()->shout_volume_modifier; if (get_mutation_level(MUT_SCREAM)) return base_noise + 2 * (get_mutation_level(MUT_SCREAM) - 1); return base_noise; } void player::god_conduct(conduct_type thing_done, int level) { ::did_god_conduct(thing_done, level); } void player::banish(actor* /*agent*/, const string &who, const int power, bool force) { ASSERT(!crawl_state.game_is_arena()); if (brdepth[BRANCH_ABYSS] == -1) return; if (elapsed_time <= attribute[ATTR_BANISHMENT_IMMUNITY]) { mpr("You resist the pull of the Abyss."); return; } if (!force && player_in_branch(BRANCH_ABYSS) && x_chance_in_y(you.depth, brdepth[BRANCH_ABYSS])) { mpr("You wobble for a moment."); return; } banished = true; banished_by = who; banished_power = power; } // Currently a no-op, previously was used for vampire hunger modifications. // Perhaps in the fullness of time this can be removed. int calc_hunger(int food_cost) { return food_cost; } /* * Approximate the loudest noise the player heard in the last * turn, possibly rescaling. This gets updated every * `world_reacts`. If `adjusted` is set to true, this rescales * noise on a 0-1000 scale according to some breakpoints that * I have hand-calibrated. Otherwise, it returns the raw noise * value (approximately from 0 to 40). The breakpoints aim to * approximate 1x los radius, 2x los radius, and 3x los radius * relative to an open area. * * @param adjusted Whether to rescale the noise level. * * @return The (scaled or unscaled) noise level heard by the player. */ int player::get_noise_perception(bool adjusted) const { // los_noise_last_turn is already normalized for the branch's ambient // noise. const int level = los_noise_last_turn; static const int BAR_MAX = 1000; // TODO: export to output.cc & webtiles if (!adjusted) return (level + 500) / BAR_MAX; static const vector<int> NOISE_BREAKPOINTS = { 0, 6000, 13000, 29000 }; const int BAR_FRAC = BAR_MAX / (NOISE_BREAKPOINTS.size() - 1); for (size_t i = 1; i < NOISE_BREAKPOINTS.size(); ++i) { const int breakpoint = NOISE_BREAKPOINTS[i]; if (level > breakpoint) continue; // what fragment of this breakpoint does the noise fill up? const int prev_break = NOISE_BREAKPOINTS[i-1]; const int break_width = breakpoint - prev_break; const int in_segment = (level - prev_break) * BAR_FRAC / break_width; // that fragment + previous breakpoints passed is our total noise. return in_segment + (i - 1) * BAR_FRAC; // example: 10k noise. that's 4k past the 6k breakpoint // ((10k-6k) * 333 / (13k - 6k)) + 333, or a bit more than half the bar } return BAR_MAX; } bool player::paralysed() const { return duration[DUR_PARALYSIS]; } bool player::cannot_move() const { return paralysed() || petrified(); } bool player::confused() const { return duration[DUR_CONF]; } bool player::caught() const { return attribute[ATTR_HELD]; } bool player::petrifying() const { return duration[DUR_PETRIFYING]; } bool player::petrified() const { return duration[DUR_PETRIFIED]; } bool player::liquefied_ground() const { return liquefied(pos()) && ground_level() && !is_insubstantial(); } int player::shield_block_penalty() const { return 5 * shield_blocks * shield_blocks; } /** * Returns whether the player currently has any kind of shield. * * XXX: why does this function exist? */ bool player::shielded() const { return shield() || duration[DUR_DIVINE_SHIELD] || get_mutation_level(MUT_LARGE_BONE_PLATES) > 0 || qazlal_sh_boost() > 0 || you.wearing(EQ_AMULET_PLUS, AMU_REFLECTION) > 0 || you.scan_artefacts(ARTP_SHIELDING); } int player::shield_bonus() const { const int shield_class = player_shield_class(); if (shield_class <= 0) return -100; return random2avg(shield_class * 2, 2) / 3 - 1; } int player::shield_bypass_ability(int tohit) const { return 15 + tohit / 2; } void player::shield_block_succeeded(actor *foe) { actor::shield_block_succeeded(foe); shield_blocks++; practise_shield_block(); if (shield()) count_action(CACT_BLOCK, shield()->sub_type); else count_action(CACT_BLOCK, -1, BLOCK_OTHER); // non-shield block } int player::missile_deflection() const { if (attribute[ATTR_DEFLECT_MISSILES]) return 2; if (get_mutation_level(MUT_DISTORTION_FIELD) == 3 || you.wearing_ego(EQ_ALL_ARMOUR, SPARM_REPULSION) || scan_artefacts(ARTP_RMSL, true) || have_passive(passive_t::upgraded_storm_shield)) { return 1; } return 0; } void player::ablate_deflection() { if (attribute[ATTR_DEFLECT_MISSILES]) { const int power = calc_spell_power(SPELL_DEFLECT_MISSILES, true); if (one_chance_in(2 + power / 8)) { attribute[ATTR_DEFLECT_MISSILES] = 0; mprf(MSGCH_DURATION, "You feel less protected from missiles."); } } } /** * What's the base value of the penalties the player receives from their * body armour? * * Used as the base for adjusted armour penalty calculations, as well as for * stealth penalty calculations. * * @return The player's body armour's PARM_EVASION, if any, taking into account * the sturdy frame mutation that reduces encumbrance. */ int player::unadjusted_body_armour_penalty() const { const item_def *body_armour = slot_item(EQ_BODY_ARMOUR, false); if (!body_armour) return 0; // PARM_EVASION is always less than or equal to 0 return max(0, -property(*body_armour, PARM_EVASION) / 10 - get_mutation_level(MUT_STURDY_FRAME) * 2); } /** * The encumbrance penalty to the player for their worn body armour. * * @param scale A scale to multiply the result by, to avoid precision loss. * @return A penalty to EV based quadratically on body armour * encumbrance. */ int player::adjusted_body_armour_penalty(int scale) const { const int base_ev_penalty = unadjusted_body_armour_penalty(); // New formula for effect of str on aevp: (2/5) * evp^2 / (str+3) return 2 * base_ev_penalty * base_ev_penalty * (450 - skill(SK_ARMOUR, 10)) * scale / (5 * (strength() + 3)) / 450; } /** * The encumbrance penalty to the player for their worn shield. * * @param scale A scale to multiply the result by, to avoid precision loss. * @return A penalty to EV based on shield weight. */ int player::adjusted_shield_penalty(int scale) const { const item_def *shield_l = slot_item(EQ_SHIELD, false); if (!shield_l) return 0; const int base_shield_penalty = -property(*shield_l, PARM_EVASION); return max(0, ((base_shield_penalty * scale) - skill(SK_SHIELDS, scale) / player_shield_racial_factor() * 10) / 10); } float player::get_shield_skill_to_offset_penalty(const item_def &item) { int evp = property(item, PARM_EVASION); return -1 * evp * player_shield_racial_factor() / 10.0; } int player::armour_tohit_penalty(bool random_factor, int scale) const { return maybe_roll_dice(1, adjusted_body_armour_penalty(scale), random_factor); } int player::shield_tohit_penalty(bool random_factor, int scale) const { return maybe_roll_dice(1, adjusted_shield_penalty(scale), random_factor); } /** * Get the player's skill level for sk. * * @param scale a scale factor to multiply by. * @param real whether to return the real value, or modified value. * @param drained whether to include modification by draining. * @param temp whether to include modification by other temporary factors (e.g. heroism) */ int player::skill(skill_type sk, int scale, bool real, bool drained, bool temp) const { // If you add another enhancement/reduction, be sure to change // SkillMenuSwitch::get_help() to reflect that // wizard racechange, or upgraded old save if (is_useless_skill(sk)) return 0; // skills[sk] might not be updated yet if this is in the middle of // skill training, so make sure to use the correct value. int actual_skill = skills[sk]; unsigned int effective_points = skill_points[sk]; if (!real) effective_points += get_crosstrain_points(sk); effective_points = min(effective_points, skill_exp_needed(MAX_SKILL_LEVEL, sk)); actual_skill = calc_skill_level_change(sk, actual_skill, effective_points); int level = actual_skill * scale + get_skill_progress(sk, actual_skill, effective_points, scale); if (real) return level; if (drained && you.attribute[ATTR_XP_DRAIN]) { // skill = base * (3000 - drain) / 3000 - drain / 100 // base - ((drain * base / 3000) + drain / 100) int drain_scale = max(0, (30 * 100 - you.attribute[ATTR_XP_DRAIN]) * scale); level = skill(sk, drain_scale, real, false); return max(0, (level - 30 * scale * you.attribute[ATTR_XP_DRAIN]) / (30 * 100)); } if (penance[GOD_ASHENZARI]) { if (temp) level = max(level - 4 * scale, level / 2); } else if (ash_has_skill_boost(sk)) level = ash_skill_boost(sk, scale); if (temp && duration[DUR_HEROISM] && sk <= SK_LAST_MUNDANE) level = min(level + 5 * scale, MAX_SKILL_LEVEL * scale); return level; } int player_icemail_armour_class() { if (!you.has_mutation(MUT_ICEMAIL)) return 0; return you.duration[DUR_ICEMAIL_DEPLETED] ? 0 : ICEMAIL_MAX; } /** * How many points of AC does the player get from their sanguine armour, if * they have any? * * @return The AC bonus * 100. (For scaling.) */ int sanguine_armour_bonus() { if (!you.duration[DUR_SANGUINE_ARMOUR]) return 0; const int mut_lev = you.get_mutation_level(MUT_SANGUINE_ARMOUR); // like iridescent, but somewhat moreso (when active) return 300 + mut_lev * 300; } /** * How much AC does the player get from an unenchanted version of the given * armour? * * @param armour The armour in question. * @param scale A value to multiply the result by. (Used to avoid integer * rounding.) * @return The AC from that armour, including armour skill, mutations * & divine blessings, but not enchantments or egos. */ int player::base_ac_from(const item_def &armour, int scale) const { const int base = property(armour, PARM_AC) * scale; // [ds] effectively: ac_value * (22 + Arm) / 22, where Arm = Armour Skill. const int AC = base * (440 + skill(SK_ARMOUR, 20)) / 440; // The deformed don't fit into body armour very well. // (This includes nagas and centaurs.) if (get_armour_slot(armour) == EQ_BODY_ARMOUR && (get_mutation_level(MUT_DEFORMED) || get_mutation_level(MUT_PSEUDOPODS))) { return AC - base / 2; } return AC; } /** * What bonus AC are you getting from your species? * * Does not account for any real mutations, such as scales or thick skin, that * you may have as a result of your species. * @param temp Whether to account for transformations. * @returns how much AC you are getting from your species "fake mutations" * 100 */ int player::racial_ac(bool temp) const { // drac scales suppressed in all serious forms, except dragon if (species_is_draconian(species) && (!player_is_shapechanged() || form == transformation::dragon || !temp)) { int AC = 400 + 100 * (experience_level / 3); // max 13 if (species == SP_GREY_DRACONIAN) // no breath AC += 500; return AC; } if (!(player_is_shapechanged() && temp)) { if (species == SP_NAGA) return 100 * experience_level / 3; // max 9 else if (species == SP_GARGOYLE) { return 200 + 100 * experience_level * 2 / 5 // max 20 + 100 * max(0, experience_level - 7) * 2 / 5; } } return 0; } // Each instance of this class stores a mutation which might change a // player's AC and how much their AC should change if the player has // said mutation. class mutation_ac_changes{ public: /** * The AC a player gains from a given mutation. If the player * lacks said mutation, return 0. * * @return How much AC to give the player for the handled * mutation. */ int get_ac_change_for_mutation(){ int ac_change = 0; int mutation_level = you.get_mutation_level(mut, mutation_activation_threshold); switch (mutation_level){ case 0: ac_change = 0; break; case 1: case 2: case 3: ac_change = ac_changes[mutation_level - 1]; break; } // The output for this function is scaled differently than the UI. return ac_change * 100; } mutation_ac_changes(mutation_type mut_aug, mutation_activity_type mutation_activation_threshold_aug, vector<int> ac_changes_aug) : mut (mut_aug), mutation_activation_threshold (mutation_activation_threshold_aug), ac_changes (ac_changes_aug) { } private: mutation_type mut; mutation_activity_type mutation_activation_threshold; vector<int> ac_changes; }; // Constant vectors for the most common mutation ac results used in // all_mutation_ac_changes const vector<int> ONE_TWO_THREE = {1,2,3}; const vector<int> TWO_THREE_FOUR = {2,3,4}; vector<mutation_ac_changes> all_mutation_ac_changes = { mutation_ac_changes(MUT_GELATINOUS_BODY, mutation_activity_type::PARTIAL, ONE_TWO_THREE) ,mutation_ac_changes(MUT_TOUGH_SKIN, mutation_activity_type::PARTIAL, ONE_TWO_THREE) ,mutation_ac_changes(MUT_SHAGGY_FUR, mutation_activity_type::PARTIAL, ONE_TWO_THREE) ,mutation_ac_changes(MUT_PHYSICAL_VULNERABILITY, mutation_activity_type::PARTIAL, {-5,-10,-15}) // Scale mutations are more easily disabled (forms etc.). This appears to be for flavour reasons. // Preserved behaviour from before mutation ac was turned to data. ,mutation_ac_changes(MUT_IRIDESCENT_SCALES, mutation_activity_type::FULL, {2, 4, 6}) ,mutation_ac_changes(MUT_RUGGED_BROWN_SCALES, mutation_activity_type::FULL, ONE_TWO_THREE) ,mutation_ac_changes(MUT_ICY_BLUE_SCALES, mutation_activity_type::FULL, TWO_THREE_FOUR) ,mutation_ac_changes(MUT_MOLTEN_SCALES, mutation_activity_type::FULL, TWO_THREE_FOUR) ,mutation_ac_changes(MUT_SLIMY_GREEN_SCALES, mutation_activity_type::FULL, TWO_THREE_FOUR) ,mutation_ac_changes(MUT_THIN_METALLIC_SCALES, mutation_activity_type::FULL, TWO_THREE_FOUR) ,mutation_ac_changes(MUT_YELLOW_SCALES, mutation_activity_type::FULL, TWO_THREE_FOUR) }; /** * The AC changes the player has from mutations. * * Mostly additions from things like scales, but the physical vulnerability * mutation is also accounted for. * * @return The player's AC gain from mutation, with 100 scaling (i.e, * the returned result 100 times the UI shows as of Jan 2020) */ int player::ac_changes_from_mutations() const { int AC = 0; for (vector<mutation_ac_changes>::iterator it = all_mutation_ac_changes.begin(); it != all_mutation_ac_changes.end(); ++it) { AC += it->get_ac_change_for_mutation(); } return AC; } /** * Get a vector with the items of armour the player is wearing. * * @return A vector of non-null pointers to all armour the player has equipped. */ vector<const item_def *> player::get_armour_items() const { vector<const item_def *> armour_items; for (int eq = EQ_MIN_ARMOUR; eq <= EQ_MAX_ARMOUR; ++eq) { if (!slot_item(static_cast<equipment_type>(eq))) continue; armour_items.push_back(&inv[equip[eq]]); } return armour_items; } /** * Get a vector with the items of armour the player would be wearing * if they put on a specific piece of armour * * @param The item which the player would be wearing in this theoretical * situation. * @return A vector of non-null pointers to all armour the player would have * equipped. */ vector<const item_def *> player::get_armour_items_one_sub(const item_def& sub) const { vector<const item_def *> armour_items = get_armour_items_one_removal(sub); armour_items.push_back(&sub); return armour_items; } /** * Get a vector with the items of armour the player would be wearing * if they removed a specific piece of armour * * @param The item which the player would be remove in this theoretical * situation. * @return A vector of non-null pointers to all armour the player would have * equipped after removing the item passed in. */ vector<const item_def *> player::get_armour_items_one_removal(const item_def& remove) const { vector<const item_def *> armour_items; for (int eq = EQ_MIN_ARMOUR; eq <= EQ_MAX_ARMOUR; ++eq) { if (get_armour_slot(remove) == eq) continue; if (!slot_item(static_cast<equipment_type>(eq))) continue; armour_items.push_back(&inv[equip[eq]]); } return armour_items; } /** * Get the players "base" ac, assuming they are wearing a particular set of * armour items (which isn't necessarily the set of armour items they are * currently wearing.) * * @param A scale by which the player's base AC is multiplied. * @param A list of items to assume the player is wearing. * @return The player's AC, multiplied by the given scale. */ int player::base_ac_with_specific_items(int scale, vector<const item_def *> armour_items) const { int AC = 0; for (auto item : armour_items) { // Shields give SH instead of AC if (get_armour_slot(*item) != EQ_SHIELD) { AC += base_ac_from(*item, 100); AC += item->plus * 100; } if (get_armour_ego_type(*item) == SPARM_PROTECTION) AC += 300; } AC += wearing(EQ_RINGS_PLUS, RING_PROTECTION) * 100; //XXX: This doesn't take into account armour_items, so an unrand shield // with +AC would have a buggy display. AC += scan_artefacts(ARTP_AC) * 100; AC += get_form()->get_ac_bonus(); AC += racial_ac(true); AC += ac_changes_from_mutations(); return AC * scale / 100; } /** * The player's "base" armour class, before transitory buffs are applied. * * (This is somewhat arbitrarily defined - forms, for example, are considered * to be long-lived for these purposes.) * * @param A scale by which the player's base AC is multiplied. * @return The player's AC, multiplied by the given scale. */ int player::base_ac(int scale) const { vector<const item_def *> armour_items = get_armour_items(); return base_ac_with_specific_items(scale, armour_items); } int player::armour_class(bool /*calc_unid*/) const { return armour_class_with_specific_items(get_armour_items()); } int player::armour_class_with_one_sub(item_def sub) const { return armour_class_with_specific_items( get_armour_items_one_sub(sub)); } int player::armour_class_with_one_removal(item_def removed) const { return armour_class_with_specific_items( get_armour_items_one_removal(removed)); } int player::armour_class_with_specific_items(vector<const item_def *> items) const { const int scale = 100; int AC = base_ac_with_specific_items(scale, items); if (duration[DUR_ICY_ARMOUR]) AC += 500 + you.props[ICY_ARMOUR_KEY].get_int() * 8; if (has_mutation(MUT_ICEMAIL)) AC += 100 * player_icemail_armour_class(); if (duration[DUR_QAZLAL_AC]) AC += 300; if (duration[DUR_SPWPN_PROTECTION]) AC += 700; if (duration[DUR_CORROSION]) AC -= 400 * you.props["corrosion_amount"].get_int(); AC += sanguine_armour_bonus(); return AC / scale; } /** * Guaranteed damage reduction. * * The percentage of the damage received that is guaranteed to be reduced * by the armour. As the AC roll is done before GDR is applied, GDR is only * useful when the AC roll is inferior to it. Therefore a higher GDR means * more damage reduced, but also more often. * * \f[ GDR = 14 \times (base\_AC - 2)^\frac{1}{2} \f] * * \return GDR as a percentage. **/ int player::gdr_perc() const { switch (form) { case transformation::dragon: return 34; // base AC 8 case transformation::statue: return 39; // like plate (AC 10) case transformation::tree: return 48; default: break; } const item_def *body_armour = slot_item(EQ_BODY_ARMOUR, false); int body_base_AC = (species == SP_GARGOYLE ? 5 : 0); if (body_armour) body_base_AC += property(*body_armour, PARM_AC); // We take a sqrt here because damage prevented by GDR is // actually proportional to the square of the GDR percentage // (assuming you have enough AC). int gdr = 14 * sqrt(max(body_base_AC - 2, 0)); return gdr; } /** * What is the player's actual, current EV, possibly relative to an attacker, * including various temporary penalties? * * @param evit Penalty types which should be excluded from the calculation. * @param act The creature that the player is attempting to evade, if any. * May be null. * @return The player's relevant EV. */ int player::evasion(ev_ignore_type evit, const actor* act) const { const int base_evasion = _player_evasion(evit); const int constrict_penalty = is_constricted() ? 3 : 0; const bool attacker_invis = act && !act->visible_to(this); const int invis_penalty = attacker_invis && !testbits(evit, ev_ignore::helpless) ? 10 : 0; return base_evasion - constrict_penalty - invis_penalty; } bool player::heal(int amount) { ::inc_hp(amount); return true; /* TODO Check whether the player was healed. */ } /** * What is the player's (current) mon_holy_type category? * Stays up to date with god for evil/unholy * Nonliving (statues, etc), undead, or alive. * * @param temp Whether to consider temporary effects: forms, * petrification... * @return The player's holiness category. */ mon_holy_type player::holiness(bool temp) const { mon_holy_type holi; // Lich form takes precedence over a species' base holiness // Alive Vampires are MH_NATURAL if (is_lifeless_undead(temp)) holi = MH_UNDEAD; else if (species == SP_GARGOYLE) holi = MH_NONLIVING; else holi = MH_NATURAL; // Petrification takes precedence over base holiness and lich form if (temp && (form == transformation::statue || form == transformation::wisp || petrified())) { holi = MH_NONLIVING; } if (is_good_god(religion)) holi |= MH_HOLY; if (is_evil_god(religion) || species == SP_DEMONSPAWN || species == SP_VAMPIRE) { holi |= MH_EVIL; } // possible XXX: Monsters get evil/unholy bits set on spell selection // should players? return holi; } bool player::undead_or_demonic() const { // This is only for TSO-related stuff, so demonspawn are included. return undead_state() || species == SP_DEMONSPAWN; } bool player::is_holy(bool /*check_spells*/) const { return bool(holiness() & MH_HOLY); } bool player::is_nonliving(bool temp) const { return bool(holiness(temp) & MH_NONLIVING); } // This is a stub. Check is used only for silver damage. Worship of chaotic // gods should probably be checked in the non-existing player::is_unclean, // which could be used for something Zin-related (such as a priestly monster). int player::how_chaotic(bool /*check_spells_god*/) const { return 0; } /** * Does the player need to breathe? * * Pretty much only matters for mephitic clouds, & confusing spores, & curare. * * @return Whether the player has no need to breathe. */ bool player::is_unbreathing() const { return !get_form()->breathes || petrified() || get_mutation_level(MUT_UNBREATHING); } bool player::is_insubstantial() const { return form == transformation::wisp; } int player::res_acid(bool calc_unid) const { return player_res_acid(calc_unid); } int player::res_fire() const { return player_res_fire(); } int player::res_steam() const { return player_res_steam(); } int player::res_cold() const { return player_res_cold(); } int player::res_elec() const { return player_res_electricity(); } int player::res_water_drowning() const { int rw = 0; if (is_unbreathing() || species_can_swim(species) && !form_changed_physiology() || form == transformation::ice_beast || form == transformation::hydra) { rw++; } return rw; } int player::res_poison(bool temp) const { return player_res_poison(true, temp); } rot_resistance player::res_rotting(bool temp) const { if (get_mutation_level(MUT_ROT_IMMUNITY) || is_nonliving(temp) || temp && get_form()->res_rot()) { return ROT_RESIST_FULL; } const item_def *armour = slot_item(EQ_BODY_ARMOUR); const bool embraced = armour && is_unrandom_artefact(*armour, UNRAND_EMBRACE); const rot_resistance base_res = embraced ? ROT_RESIST_MUNDANE : ROT_RESIST_NONE; switch (undead_state(temp)) { default: case US_ALIVE: return base_res; case US_HUNGRY_DEAD: return ROT_RESIST_MUNDANE; // rottable by Zin, not by necromancy case US_SEMI_UNDEAD: if (temp && !you.vampire_alive) return ROT_RESIST_MUNDANE; return base_res; case US_UNDEAD: return ROT_RESIST_FULL; } } bool player::res_sticky_flame() const { return player_res_sticky_flame(); } int player::res_holy_energy() const { if (undead_or_demonic()) return -1; if (is_holy()) return 3; return 0; } int player::res_negative_energy(bool intrinsic_only) const { return player_prot_life(!intrinsic_only, true, !intrinsic_only); } bool player::res_torment() const { return player_res_torment(); } bool player::res_tornado() const { // Full control of the winds around you can negate a hostile tornado. return duration[DUR_TORNADO] ? 1 : 0; } bool player::res_petrify(bool temp) const { return get_mutation_level(MUT_PETRIFICATION_RESISTANCE) || temp && get_form()->res_petrify(); } int player::res_constrict() const { if (is_insubstantial()) return 3; if (get_mutation_level(MUT_SPINY)) return 3; return 0; } int player::res_magic(bool /*calc_unid*/) const { return player_res_magic(); } int player_res_magic(bool calc_unid, bool temp) { if (temp && you.form == transformation::shadow) return MAG_IMMUNE; int rm = you.experience_level * species_mr_modifier(you.species); // randarts rm += MR_PIP * you.scan_artefacts(ARTP_MAGIC_RESISTANCE, calc_unid); // body armour const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR); if (body_armour) rm += armour_type_prop(body_armour->sub_type, ARMF_RES_MAGIC) * MR_PIP; // ego armours rm += MR_PIP * you.wearing_ego(EQ_ALL_ARMOUR, SPARM_MAGIC_RESISTANCE, calc_unid); // rings of magic resistance rm += MR_PIP * you.wearing(EQ_RINGS, RING_PROTECTION_FROM_MAGIC, calc_unid); // Mutations rm += MR_PIP * you.get_mutation_level(MUT_MAGIC_RESISTANCE); rm -= MR_PIP * you.get_mutation_level(MUT_MAGICAL_VULNERABILITY); // transformations if (you.form == transformation::lich && temp) rm += MR_PIP; // Trog's Hand if (you.duration[DUR_TROGS_HAND] && temp) rm += MR_PIP * 2; // Enchantment effect if (you.duration[DUR_LOWERED_MR] && temp) rm /= 2; if (rm < 0) rm = 0; return rm; } /** * Is the player prevented from teleporting? If so, why? * * @param calc_unid Whether to identify unknown items that prevent tele * (probably obsolete) * @param blinking Are you blinking or teleporting? * @return Why the player is prevented from teleporting, if they * are; else, the empty string. */ string player::no_tele_reason(bool calc_unid, bool blinking) const { if (!blinking) { if (crawl_state.game_is_sprint()) return "Long-range teleportation is disallowed in Dungeon Sprint."; else if (player_in_branch(BRANCH_GAUNTLET)) { return "A magic seal in the Gauntlet prevents long-range " "teleports."; } } if (stasis()) return "Your stasis prevents you from teleporting."; vector<string> problems; if (duration[DUR_DIMENSION_ANCHOR]) problems.emplace_back("locked down by a dimension anchor"); if (form == transformation::tree) problems.emplace_back("held in place by your roots"); vector<const item_def *> notele_items; if (has_notele_item(calc_unid, &notele_items)) { vector<string> worn_notele; bool found_nonartefact = false; for (const auto item : notele_items) { if (item->base_type == OBJ_WEAPONS) { problems.push_back(make_stringf("wielding %s", item->name(DESC_A).c_str())); } else worn_notele.push_back(item->name(DESC_A)); } if (worn_notele.size() > (problems.empty() ? 3 : 1)) { problems.push_back( make_stringf("wearing %s %s preventing teleportation", number_in_words(worn_notele.size()).c_str(), found_nonartefact ? "items": "artefacts")); } else if (!worn_notele.empty()) { problems.push_back( make_stringf("wearing %s", comma_separated_line(worn_notele.begin(), worn_notele.end()).c_str())); } } if (problems.empty()) return ""; // no problem return make_stringf("You cannot %s because you are %s.", blinking ? "blink" : "teleport", comma_separated_line(problems.begin(), problems.end()).c_str()); } /** * Is the player prevented from teleporting/blinking right now? If so, * print why. * * @param calc_unid Whether to identify unknown items that prevent tele * (probably obsolete) * @param blinking Are you blinking or teleporting? * @return Whether the player is prevented from teleportation. */ bool player::no_tele_print_reason(bool calc_unid, bool blinking) const { const string reason = no_tele_reason(calc_unid, blinking); if (reason.empty()) return false; mpr(reason); return true; } /** * Is the player prevented from teleporting/blinking right now? * * @param calc_unid Whether to identify unknown items that prevent tele * (probably obsolete) * @param permit_id Unused for players. * @param blinking Are you blinking or teleporting? * @return Whether the player is prevented from teleportation. */ bool player::no_tele(bool calc_unid, bool /*permit_id*/, bool blinking) const { return !no_tele_reason(calc_unid, blinking).empty(); } bool player::fights_well_unarmed(int heavy_armour_penalty) { return x_chance_in_y(skill(SK_UNARMED_COMBAT, 10), 200) && x_chance_in_y(2, 1 + heavy_armour_penalty); } bool player::cancellable_flight() const { return duration[DUR_FLIGHT] && !permanent_flight() && !attribute[ATTR_FLIGHT_UNCANCELLABLE]; } bool player::permanent_flight() const { return attribute[ATTR_PERM_FLIGHT]; } bool player::racial_permanent_flight() const { return get_mutation_level(MUT_TENGU_FLIGHT) || get_mutation_level(MUT_BIG_WINGS); } bool player::tengu_flight() const { // Only Tengu get perks for flying. return species == SP_TENGU && airborne(); } /** * Returns true if player spellcasting is considered unholy. * * Checks to see if the player is wielding the Majin-Bo. * * @return Whether player spellcasting is an unholy act. */ bool player::spellcasting_unholy() const { return player_equip_unrand(UNRAND_MAJIN); } /** * What is the player's (current) place on the Undead Spectrum? * (alive, hungry undead (ghoul), semi-undead (vampire), or very dead (mummy, * lich) * * @param temp Whether to consider temporary effects (lichform) * @return The player's undead state. */ undead_state_type player::undead_state(bool temp) const { if (temp && you.form == transformation::lich) return US_UNDEAD; return species_undead_type(you.species); } bool player::nightvision() const { return have_passive(passive_t::nightvision); } reach_type player::reach_range() const { const item_def *wpn = weapon(); if (wpn) return weapon_reach(*wpn); return REACH_NONE; } monster_type player::mons_species(bool /*zombie_base*/) const { return player_species_to_mons_species(species); } bool player::poison(actor *agent, int amount, bool force) { return ::poison_player(amount, agent? agent->name(DESC_A, true) : "", "", force); } void player::expose_to_element(beam_type element, int _strength, bool slow_cold_blood) { ::expose_player_to_element(element, _strength, slow_cold_blood); } void player::blink() { cast_blink(); } void player::teleport(bool now, bool wizard_tele) { ASSERT(!crawl_state.game_is_arena()); if (now) you_teleport_now(wizard_tele); else you_teleport(); } int player::hurt(const actor *agent, int amount, beam_type flavour, kill_method_type kill_type, string source, string aux, bool /*cleanup_dead*/, bool /*attacker_effects*/) { // We ignore cleanup_dead here. if (!agent) { // FIXME: This can happen if a deferred_damage_fineff does damage // to a player from a dead monster. We should probably not do that, // but it could be tricky to fix, so for now let's at least avoid // a crash even if it does mean funny death messages. ouch(amount, kill_type, MID_NOBODY, aux.c_str(), false, source.c_str()); } else { ouch(amount, kill_type, agent->mid, aux.c_str(), agent->visible_to(this), source.c_str()); } if ((flavour == BEAM_DEVASTATION || flavour == BEAM_DISINTEGRATION) && can_bleed()) { blood_spray(pos(), type, amount / 5); } return amount; } void player::drain_stat(stat_type s, int amount) { lose_stat(s, amount); } bool player::rot(actor */*who*/, int amount, bool quiet, bool /*no_cleanup*/) { ASSERT(!crawl_state.game_is_arena()); if (amount <= 0) return false; if (res_rotting() || duration[DUR_DEATHS_DOOR]) { mpr("You feel terrible."); return false; } if (duration[DUR_DIVINE_STAMINA] > 0) { mpr("Your divine stamina protects you from decay!"); return false; } rot_hp(amount); if (!quiet) mprf(MSGCH_WARN, "You feel your flesh rotting away!"); learned_something_new(HINT_YOU_ROTTING); if (one_chance_in(4)) sicken(50 + random2(100)); return true; } bool player::corrode_equipment(const char* corrosion_source, int degree) { // rCorr protects against 50% of corrosion. if (res_corr()) { degree = binomial(degree, 50); if (!degree) { dprf("rCorr protects."); return false; } } // always increase duration, but... increase_duration(DUR_CORROSION, 10 + roll_dice(2, 4), 50, make_stringf("%s corrodes you!", corrosion_source).c_str()); // the more corrosion you already have, the lower the odds of more int prev_corr = props["corrosion_amount"].get_int(); bool did_corrode = false; for (int i = 0; i < degree; i++) if (!x_chance_in_y(prev_corr, prev_corr + 7)) { props["corrosion_amount"].get_int()++; prev_corr++; did_corrode = true; } if (did_corrode) { redraw_armour_class = true; wield_change = true; } return true; } /** * Attempts to apply corrosion to the player and deals acid damage. * * @param evildoer the cause of this acid splash. * @param acid_strength The strength of the acid. * @param allow_corrosion Whether to try and apply the corrosion debuff. * @param hurt_msg A message to display when dealing damage. */ void player::splash_with_acid(const actor* evildoer, int acid_strength, bool allow_corrosion, const char* /*hurt_msg*/) { if (allow_corrosion && binomial(3, acid_strength + 1, 30)) corrode_equipment(); const int dam = roll_dice(4, acid_strength); const int post_res_dam = resist_adjust_damage(&you, BEAM_ACID, dam); mprf("You are splashed with acid%s%s", post_res_dam > 0 ? "" : " but take no damage", attack_strength_punctuation(post_res_dam).c_str()); if (post_res_dam > 0) { if (post_res_dam < dam) canned_msg(MSG_YOU_RESIST); ouch(post_res_dam, KILLED_BY_ACID, evildoer ? evildoer->mid : MID_NOBODY); } } bool player::drain_exp(actor */*who*/, bool quiet, int pow) { return drain_player(pow, !quiet); } void player::confuse(actor */*who*/, int str) { confuse_player(str); } /** * Paralyse the player for str turns. * * Duration is capped at 13. * * @param who Pointer to the actor who paralysed the player. * @param str The number of turns the paralysis will last. * @param source Description of the source of the paralysis. */ void player::paralyse(actor *who, int str, string source) { ASSERT(!crawl_state.game_is_arena()); if (stasis()) { mpr("Your stasis prevents you from being paralysed."); return; } // The who check has an effect in a few cases, most notably making // Death's Door + Borg's paralysis unblockable. if (who && (duration[DUR_PARALYSIS] || duration[DUR_PARALYSIS_IMMUNITY])) { mpr("You shrug off the repeated paralysis!"); return; } int &paralysis(duration[DUR_PARALYSIS]); const bool use_actor_name = source.empty() && who != nullptr; if (use_actor_name) source = who->name(DESC_A); if (!paralysis && !source.empty()) { take_note(Note(NOTE_PARALYSIS, str, 0, source)); // use the real name here even for invisible monsters props[PARALYSED_BY_KEY] = use_actor_name ? who->name(DESC_A, true) : source; } if (asleep()) you.awaken(); mpr("You suddenly lose the ability to move!"); paralysis = min(str, 13) * BASELINE_DELAY; stop_directly_constricting_all(false); end_searing_ray(); } void player::petrify(actor *who, bool force) { ASSERT(!crawl_state.game_is_arena()); if (res_petrify() && !force) { canned_msg(MSG_YOU_UNAFFECTED); return; } if (duration[DUR_DIVINE_STAMINA] > 0) { mpr("Your divine stamina protects you from petrification!"); return; } // Petrification always wakes you up if (asleep()) you.awaken(); if (petrifying()) { mpr("Your limbs have turned to stone."); duration[DUR_PETRIFYING] = 1; return; } if (petrified()) return; duration[DUR_PETRIFYING] = 3 * BASELINE_DELAY; if (who) props[PETRIFIED_BY_KEY] = who->name(DESC_A, true); redraw_evasion = true; mprf(MSGCH_WARN, "You are slowing down."); } bool player::fully_petrify(actor */*foe*/, bool /*quiet*/) { duration[DUR_PETRIFIED] = 6 * BASELINE_DELAY + random2(4 * BASELINE_DELAY); redraw_evasion = true; mpr("You have turned to stone."); end_searing_ray(); return true; } void player::slow_down(actor */*foe*/, int str) { ::slow_player(str); } int player::has_claws(bool allow_tran) const { if (allow_tran) { // these transformations bring claws with them if (form == transformation::dragon) return 3; // blade hands override claws if (form == transformation::blade_hands) return 0; } return get_mutation_level(MUT_CLAWS, allow_tran); } bool player::has_usable_claws(bool allow_tran) const { return !slot_item(EQ_GLOVES) && has_claws(allow_tran); } int player::has_talons(bool allow_tran) const { // XXX: Do merfolk in water belong under allow_tran? if (fishtail) return 0; return get_mutation_level(MUT_TALONS, allow_tran); } bool player::has_usable_talons(bool allow_tran) const { return !slot_item(EQ_BOOTS) && has_talons(allow_tran); } int player::has_hooves(bool allow_tran) const { // XXX: Do merfolk in water belong under allow_tran? if (fishtail) return 0; return get_mutation_level(MUT_HOOVES, allow_tran); } bool player::has_usable_hooves(bool allow_tran) const { return has_hooves(allow_tran) && (!slot_item(EQ_BOOTS) || wearing(EQ_BOOTS, ARM_CENTAUR_BARDING, true)); } int player::has_fangs(bool allow_tran) const { if (allow_tran) { // these transformations bring fangs with them if (form == transformation::dragon) return 3; } return get_mutation_level(MUT_FANGS, allow_tran); } int player::has_usable_fangs(bool allow_tran) const { return has_fangs(allow_tran); } int player::has_tail(bool allow_tran) const { if (allow_tran) { // these transformations bring a tail with them if (form == transformation::dragon) return 1; // Most transformations suppress a tail. if (!form_keeps_mutations()) return 0; } // XXX: Do merfolk in water belong under allow_tran? if (species_is_draconian(species) || fishtail || get_mutation_level(MUT_STINGER, allow_tran)) { return 1; } return 0; } int player::has_usable_tail(bool allow_tran) const { return has_tail(allow_tran); } // Whether the player has a usable offhand for the // purpose of punching. bool player::has_usable_offhand() const { if (get_mutation_level(MUT_MISSING_HAND)) return false; if (shield()) return false; const item_def* wp = slot_item(EQ_WEAPON); return !wp || hands_reqd(*wp) != HANDS_TWO; } bool player::has_usable_tentacle() const { return usable_tentacles(); } int player::usable_tentacles() const { int numtentacle = has_usable_tentacles(); if (numtentacle == 0) return false; int free_tentacles = numtentacle - num_constricting(); if (shield()) free_tentacles -= 2; const item_def* wp = slot_item(EQ_WEAPON); if (wp) { hands_reqd_type hands_req = hands_reqd(*wp); free_tentacles -= 2 * hands_req + 2; } return free_tentacles; } int player::has_pseudopods(bool allow_tran) const { return get_mutation_level(MUT_PSEUDOPODS, allow_tran); } int player::has_usable_pseudopods(bool allow_tran) const { return has_pseudopods(allow_tran); } int player::has_tentacles(bool allow_tran) const { if (allow_tran) { // Most transformations suppress tentacles. if (!form_keeps_mutations()) return 0; } if (species == SP_OCTOPODE && get_mutation_level(MUT_MISSING_HAND)) return 7; else if (species == SP_OCTOPODE) return 8; return 0; } int player::has_usable_tentacles(bool allow_tran) const { return has_tentacles(allow_tran); } bool player::sicken(int amount) { ASSERT(!crawl_state.game_is_arena()); if (res_rotting() || amount <= 0) return false; if (duration[DUR_DIVINE_STAMINA] > 0) { mpr("Your divine stamina protects you from disease!"); return false; } mpr("You feel ill."); disease += amount * BASELINE_DELAY; if (disease > 210 * BASELINE_DELAY) disease = 210 * BASELINE_DELAY; return true; } /// Can the player see invisible things? bool player::can_see_invisible(bool calc_unid) const { if (crawl_state.game_is_arena()) return true; if (wearing(EQ_RINGS, RING_SEE_INVISIBLE, calc_unid) // armour: (checks head armour only) || wearing_ego(EQ_HELMET, SPARM_SEE_INVISIBLE) // randart gear || scan_artefacts(ARTP_SEE_INVISIBLE, calc_unid) > 0) { return true; } return innate_sinv(); } /// Can the player see invisible things without needing items' help? bool player::innate_sinv() const { // Possible to have both with a temp mutation. if (has_mutation(MUT_ACUTE_VISION) && !has_mutation(MUT_BLURRY_VISION)) { return true; } // antennae give sInvis at 3 if (get_mutation_level(MUT_ANTENNAE) == 3) return true; if (get_mutation_level(MUT_EYEBALLS) == 3) return true; if (have_passive(passive_t::sinv)) return true; return false; } bool player::invisible() const { return (duration[DUR_INVIS] || form == transformation::shadow) && !backlit(); } bool player::visible_to(const actor *looker) const { if (crawl_state.game_is_arena()) return false; const bool invis_to = invisible() && !looker->can_see_invisible() && !in_water(); if (this == looker) return !invis_to; const monster* mon = looker->as_monster(); return mon->friendly() || (!mon->has_ench(ENCH_BLIND) && !invis_to); } /** * Is the player backlit? * * @param self_halo If true, ignore the player's self-halo. * @returns True if the player is backlit. */ bool player::backlit(bool self_halo) const { return player_severe_contamination() || duration[DUR_CORONA] || duration[DUR_LIQUID_FLAMES] || duration[DUR_QUAD_DAMAGE] || !umbraed() && haloed() && (self_halo || halo_radius() == -1); } bool player::umbra() const { return !backlit() && umbraed() && !haloed(); } // This is the imperative version. void player::backlight() { if (!duration[DUR_INVIS] && form != transformation::shadow) { if (duration[DUR_CORONA]) mpr("You glow brighter."); else mpr("You are outlined in light."); increase_duration(DUR_CORONA, random_range(15, 35), 250); } else { mpr("You feel strangely conspicuous."); increase_duration(DUR_CORONA, random_range(3, 5), 250); } } bool player::can_mutate() const { return true; } /** * Can the player be mutated without rotting instead? * * @param temp Whether to consider temporary modifiers (lichform) * @return Whether the player will mutate when mutated, instead of rotting. */ bool player::can_safely_mutate(bool temp) const { if (!can_mutate()) return false; return undead_state(temp) == US_ALIVE || undead_state(temp) == US_SEMI_UNDEAD; } // Is the player too undead to bleed, rage, or polymorph? bool player::is_lifeless_undead(bool temp) const { if (undead_state() == US_SEMI_UNDEAD) return temp ? !you.vampire_alive : false; else return undead_state(temp) != US_ALIVE; } bool player::can_polymorph() const { return !(transform_uncancellable || is_lifeless_undead()); } bool player::can_bleed(bool allow_tran) const { // XXX: Lich and statue forms are still caught by the holiness checks below. if (allow_tran && !form_can_bleed(form)) return false; if (is_lifeless_undead() || is_nonliving()) { // demonspawn and demigods have a mere drop of taint return false; } return true; } bool player::is_stationary() const { return form == transformation::tree; } bool player::malmutate(const string &reason) { ASSERT(!crawl_state.game_is_arena()); if (!can_mutate()) return false; const mutation_type mut_quality = one_chance_in(5) ? RANDOM_MUTATION : RANDOM_BAD_MUTATION; if (mutate(mut_quality, reason)) { learned_something_new(HINT_YOU_MUTATED); return true; } return false; } bool player::polymorph(int pow, bool allow_immobile) { ASSERT(!crawl_state.game_is_arena()); if (!can_polymorph()) return false; transformation f = transformation::none; vector<transformation> forms = { transformation::bat, transformation::wisp, transformation::pig, }; if (allow_immobile) { forms.emplace_back(transformation::tree); forms.emplace_back(transformation::fungus); } for (int tries = 0; tries < 3; tries++) { f = forms[random2(forms.size())]; // need to do a dry run first, as Zin's protection has a random factor if (transform(pow, f, true, true)) break; f = transformation::none; } if (f != transformation::none && transform(pow, f)) { transform_uncancellable = true; return true; } return false; } bool player::is_icy() const { return form == transformation::ice_beast; } bool player::is_fiery() const { return false; } bool player::is_skeletal() const { return false; } void player::shiftto(const coord_def &c) { crawl_view.shift_player_to(c); set_position(c); clear_invalid_constrictions(); } bool player::asleep() const { return duration[DUR_SLEEP]; } bool player::cannot_act() const { return asleep() || cannot_move(); } bool player::can_throw_large_rocks() const { return species_can_throw_large_rocks(species); } bool player::can_smell() const { return species != SP_MUMMY; } bool player::can_sleep(bool holi_only) const { return !you.duration[DUR_SLEEP_IMMUNITY] && actor::can_sleep(holi_only); } /** * Attempts to put the player to sleep. * * @param power The power of the effect putting the player to sleep. * @param hibernate Whether the player is being put to sleep by 'ensorcelled * hibernation' (doesn't affect characters with rC, ignores * power), or by a normal sleep effect. */ void player::put_to_sleep(actor*, int power, bool hibernate) { ASSERT(!crawl_state.game_is_arena()); const bool valid_target = hibernate ? can_hibernate() : can_sleep(); if (!valid_target) { canned_msg(MSG_YOU_UNAFFECTED); return; } if (duration[DUR_SLEEP_IMMUNITY]) { mpr("You can't fall asleep again this soon!"); return; } if (duration[DUR_PARALYSIS] || duration[DUR_PETRIFIED] || duration[DUR_PETRIFYING]) { mpr("You can't fall asleep in your current state!"); return; } mpr("You fall asleep."); stop_directly_constricting_all(false); end_searing_ray(); stop_delay(); flash_view(UA_MONSTER, DARKGREY); // As above, do this after redraw. const int dur = hibernate ? 3 + random2avg(5, 2) : 5 + random2avg(power/10, 5); set_duration(DUR_SLEEP, dur); } void player::awaken() { ASSERT(!crawl_state.game_is_arena()); duration[DUR_SLEEP] = 0; set_duration(DUR_SLEEP_IMMUNITY, random_range(3, 5)); mpr("You wake up."); flash_view(UA_MONSTER, BLACK); } void player::check_awaken(int disturbance) { if (asleep() && x_chance_in_y(disturbance + 1, 50)) { awaken(); dprf("Disturbance of intensity %d awoke player", disturbance); } } int player::beam_resists(bolt &beam, int hurted, bool doEffects, string source) { return check_your_resists(hurted, beam.flavour, source, &beam, doEffects); } // Used for falling into traps and other bad effects, but is a slightly // different effect from the player invokable ability. bool player::do_shaft() { if (!is_valid_shaft_level() || !feat_is_shaftable(grd(pos())) || duration[DUR_SHAFT_IMMUNITY]) { return false; } // Ensure altars, items, and shops discovered at the moment // the player gets shafted are correctly registered. maybe_update_stashes(); duration[DUR_SHAFT_IMMUNITY] = 1; down_stairs(DNGN_TRAP_SHAFT); return true; } bool player::can_do_shaft_ability(bool quiet) const { if (attribute[ATTR_HELD]) { if (!quiet) mprf("You can't shaft yourself while %s.", held_status()); return false; } if (feat_is_shaftable(grd(pos()))) { if (!is_valid_shaft_level()) { if (!quiet) mpr("You can't shaft yourself on this level."); return false; } } else { if (!quiet) mpr("You can't shaft yourself on this terrain."); return false; } return true; } // Like do_shaft, but forced by the player. // It has a slightly different set of rules. bool player::do_shaft_ability() { if (can_do_shaft_ability(true)) { mpr("A shaft appears beneath you!"); down_stairs(DNGN_TRAP_SHAFT, true); return true; } else { canned_msg(MSG_NOTHING_HAPPENS); redraw_screen(); return false; } } bool player::did_escape_death() const { return escaped_death_cause != NUM_KILLBY; } void player::reset_escaped_death() { escaped_death_cause = NUM_KILLBY; escaped_death_aux = ""; } void player::add_gold(int delta) { set_gold(gold + delta); } void player::del_gold(int delta) { set_gold(gold - delta); } void player::set_gold(int amount) { ASSERT(amount >= 0); if (amount != gold) { const int old_gold = gold; gold = amount; shopping_list.gold_changed(old_gold, gold); // XXX: this might benefit from being in its own function if (you_worship(GOD_GOZAG)) { for (const auto& power : get_god_powers(you.religion)) { const int cost = get_gold_cost(power.abil); if (gold >= cost && old_gold < cost) power.display(true, "You now have enough gold to %s."); else if (old_gold >= cost && gold < cost) power.display(false, "You no longer have enough gold to %s."); } you.redraw_title = true; } } } void player::increase_duration(duration_type dur, int turns, int cap, const char* msg) { if (msg) mpr(msg); cap *= BASELINE_DELAY; duration[dur] += turns * BASELINE_DELAY; if (cap && duration[dur] > cap) duration[dur] = cap; } void player::set_duration(duration_type dur, int turns, int cap, const char * msg) { duration[dur] = 0; increase_duration(dur, turns, cap, msg); } void player::goto_place(const level_id &lid) { where_are_you = static_cast<branch_type>(lid.branch); depth = lid.depth; ASSERT_RANGE(depth, 1, brdepth[where_are_you] + 1); } bool player::attempt_escape(int attempts) { monster *themonst; if (!is_constricted()) return true; themonst = monster_by_mid(constricted_by); ASSERT(themonst); escape_attempts += attempts; const bool direct = is_directly_constricted(); const string object = direct ? themonst->name(DESC_ITS, true) : "the roots'"; // player breaks free if (4+n)d13 >= 5d(8+HD/4) const int escape_score = roll_dice(4 + escape_attempts, 13); if (escape_score >= roll_dice(5, 8 + div_rand_round(themonst->get_hit_dice(), 4))) { mprf("You escape %s grasp.", object.c_str()); // Stun the monster to prevent it from constricting again right away. if (direct) themonst->speed_increment -= 5; stop_being_constricted(true); return true; } else { mprf("%s grasp on you weakens, but your attempt to escape fails.", object.c_str()); turn_is_over = true; return false; } } void player::sentinel_mark(bool trap) { if (duration[DUR_SENTINEL_MARK]) { mpr("The mark upon you grows brighter."); increase_duration(DUR_SENTINEL_MARK, random_range(20, 40), 180); } else { mprf(MSGCH_WARN, "A sentinel's mark forms upon you."); increase_duration(DUR_SENTINEL_MARK, trap ? random_range(25, 40) : random_range(35, 60), 250); } } /* * Is the player too terrified to move (because of fungusform)? * * @return true iff there is an alarming monster anywhere near a fungusform player. */ bool player::is_nervous() { if (form != transformation::fungus) return false; for (monster_near_iterator mi(&you); mi; ++mi) { if (made_nervous_by(*mi)) return true; } return false; } /* * Does monster `mons` make the player nervous (in fungusform)? * * @param mons the monster to check * @return true iff mons is non-null, player is fungal, and `mons` is a threatening monster. */ bool player::made_nervous_by(const monster *mons) { if (form != transformation::fungus) return false; if (!mons) return false; if (!mons_is_wandering(*mons) && !mons->asleep() && !mons->confused() && !mons->cannot_act() && mons_is_threatening(*mons) && !mons->wont_attack() && !mons->neutral()) { return true; } return false; } void player::weaken(actor */*attacker*/, int pow) { if (!duration[DUR_WEAK]) mprf(MSGCH_WARN, "You feel your attacks grow feeble."); else mprf(MSGCH_WARN, "You feel as though you will be weak longer."); increase_duration(DUR_WEAK, pow + random2(pow + 3), 50); } /** * Check if the player is about to die from flight/form expiration. * * Check whether the player is on a cell which would be deadly if not for some * temporary condition, and if such condition is expiring. In that case, we * give a strong warning to the player. The actual message printing is done * by the caller. * * @param dur the duration to check for dangerous expiration. * @param p the coordinates of the cell to check. Defaults to player position. * @return whether the player is in immediate danger. */ bool need_expiration_warning(duration_type dur, dungeon_feature_type feat) { if (!is_feat_dangerous(feat, true) || !dur_expiring(dur)) return false; if (dur == DUR_FLIGHT) return true; else if (dur == DUR_TRANSFORMATION && (form_can_swim()) || form_can_fly()) { return true; } return false; } bool need_expiration_warning(duration_type dur, coord_def p) { return need_expiration_warning(dur, env.grid(p)); } bool need_expiration_warning(dungeon_feature_type feat) { return need_expiration_warning(DUR_FLIGHT, feat) || need_expiration_warning(DUR_TRANSFORMATION, feat); } bool need_expiration_warning(coord_def p) { return need_expiration_warning(env.grid(p)); } static string _constriction_description() { string cinfo = ""; vector<string> c_name; const int num_free_tentacles = you.usable_tentacles(); if (num_free_tentacles) { cinfo += make_stringf("You have %d tentacle%s available for constriction.", num_free_tentacles, num_free_tentacles > 1 ? "s" : ""); } if (you.is_directly_constricted()) { const monster * const constrictor = monster_by_mid(you.constricted_by); ASSERT(constrictor); if (!cinfo.empty()) cinfo += "\n"; cinfo += make_stringf("You are being %s by %s.", constrictor->constriction_does_damage(true) ? "held" : "constricted", constrictor->name(DESC_A).c_str()); } if (you.is_constricting()) { for (const auto &entry : *you.constricting) { monster *whom = monster_by_mid(entry.first); ASSERT(whom); if (!whom->is_directly_constricted()) continue; c_name.push_back(whom->name(DESC_A)); } if (!c_name.empty()) { if (!cinfo.empty()) cinfo += "\n"; cinfo += "You are constricting "; cinfo += comma_separated_line(c_name.begin(), c_name.end()); cinfo += "."; } } return cinfo; } /** * The player's radius of monster detection. * @return the radius in which a player can detect monsters. **/ int player_monster_detect_radius() { int radius = you.get_mutation_level(MUT_ANTENNAE) * 2; if (player_equip_unrand(UNRAND_HOOD_ASSASSIN)) radius = max(radius, 4); if (have_passive(passive_t::detect_montier)) radius = max(radius, you.piety / 20); return min(radius, LOS_DEFAULT_RANGE); } /** * Return true if the player has angered Pandemonium by picking up or moving * the Orb of Zot. */ bool player_on_orb_run() { return you.chapter == CHAPTER_ESCAPING || you.chapter == CHAPTER_ANGERED_PANDEMONIUM; } /** * Return true if the player has the Orb of Zot. * @return True if the player has the Orb, false otherwise. */ bool player_has_orb() { return you.chapter == CHAPTER_ESCAPING; } bool player::form_uses_xl() const { // No body parts that translate in any way to something fisticuffs could // matter to, the attack mode is different. Plus, it's weird to have // users of one particular [non-]weapon be effective for this // unintentional form while others can just run or die. I believe this // should apply to more forms, too. [1KB] return form == transformation::wisp || form == transformation::fungus || form == transformation::pig || form == transformation::bat && you.species != SP_VAMPIRE; } static int _get_potion_heal_factor() { // healing factor is expressed in thirds, so default is 3/3 -- 100%. int factor = 3; // start with penalties factor -= player_equip_unrand(UNRAND_VINES) ? 3 : 0; factor -= you.mutation[MUT_NO_POTION_HEAL]; // then apply bonuses - Kryia's doubles potion healing factor *= player_equip_unrand(UNRAND_KRYIAS) ? 2 : 1; // make sure we don't turn healing negative. return max(0, factor); } void print_potion_heal_message() { // Don't give multiple messages in weird cases with both enhanced // and reduced healing. if (_get_potion_heal_factor() > 3) { if (player_equip_unrand(UNRAND_KRYIAS)) { item_def* item = you.slot_item(EQ_BODY_ARMOUR); mprf("%s enhances the healing.", item->name(DESC_THE, false, false, false).c_str()); } else mpr("The healing is enhanced."); // bad message, but this should // never be possible anyway } else if (_get_potion_heal_factor() == 0) mpr("Your system rejects the healing."); else if (_get_potion_heal_factor() < 3) mpr("Your system partially rejects the healing."); } bool player::can_potion_heal() { return _get_potion_heal_factor() > 0; } int player::scale_potion_healing(int healing_amount) { return div_rand_round(healing_amount * _get_potion_heal_factor(), 3); } void player_open_door(coord_def doorpos) { // Finally, open the closed door! set<coord_def> all_door; find_connected_identical(doorpos, all_door); const char *adj, *noun; get_door_description(all_door.size(), &adj, &noun); const string door_desc_adj = env.markers.property_at(doorpos, MAT_ANY, "door_description_adjective"); const string door_desc_noun = env.markers.property_at(doorpos, MAT_ANY, "door_description_noun"); if (!door_desc_adj.empty()) adj = door_desc_adj.c_str(); if (!door_desc_noun.empty()) noun = door_desc_noun.c_str(); if (!you.confused()) { string door_open_prompt = env.markers.property_at(doorpos, MAT_ANY, "door_open_prompt"); bool ignore_exclude = false; if (!door_open_prompt.empty()) { door_open_prompt += " (y/N)"; if (!yesno(door_open_prompt.c_str(), true, 'n', true, false)) { if (is_exclude_root(doorpos)) canned_msg(MSG_OK); else { if (yesno("Put travel exclusion on door? (Y/n)", true, 'y')) { // Zero radius exclusion right on top of door. set_exclude(doorpos, 0); } } interrupt_activity(activity_interrupt::force); return; } ignore_exclude = true; } if (!ignore_exclude && is_exclude_root(doorpos)) { string prompt = make_stringf("This %s%s is marked as excluded! " "Open it anyway?", adj, noun); if (!yesno(prompt.c_str(), true, 'n', true, false)) { canned_msg(MSG_OK); interrupt_activity(activity_interrupt::force); return; } } } const int skill = 8 + you.skill_rdiv(SK_STEALTH, 4, 3); string berserk_open = env.markers.property_at(doorpos, MAT_ANY, "door_berserk_verb_open"); string berserk_adjective = env.markers.property_at(doorpos, MAT_ANY, "door_berserk_adjective"); string door_open_creak = env.markers.property_at(doorpos, MAT_ANY, "door_noisy_verb_open"); string door_airborne = env.markers.property_at(doorpos, MAT_ANY, "door_airborne_verb_open"); string door_open_verb = env.markers.property_at(doorpos, MAT_ANY, "door_verb_open"); if (you.berserk()) { // XXX: Better flavour for larger doors? if (silenced(you.pos())) { if (!berserk_open.empty()) { berserk_open += "."; mprf(berserk_open.c_str(), adj, noun); } else mprf("The %s%s flies open!", adj, noun); } else { if (!berserk_open.empty()) { if (!berserk_adjective.empty()) berserk_open += " " + berserk_adjective; else berserk_open += "."; mprf(MSGCH_SOUND, berserk_open.c_str(), adj, noun); } else mprf(MSGCH_SOUND, "The %s%s flies open with a bang!", adj, noun); noisy(15, you.pos()); } } else if (one_chance_in(skill) && !silenced(you.pos())) { if (!door_open_creak.empty()) mprf(MSGCH_SOUND, door_open_creak.c_str(), adj, noun); else { mprf(MSGCH_SOUND, "As you open the %s%s, it creaks loudly!", adj, noun); } noisy(10, you.pos()); } else { const char* verb; if (you.airborne()) { if (!door_airborne.empty()) verb = door_airborne.c_str(); else verb = "You reach down and open the %s%s."; } else { if (!door_open_verb.empty()) verb = door_open_verb.c_str(); else verb = "You open the %s%s."; } mprf(verb, adj, noun); } vector<coord_def> excludes; for (const auto &dc : all_door) { if (cell_is_runed(dc)) explored_tracked_feature(grd(dc)); dgn_open_door(dc); set_terrain_changed(dc); dungeon_events.fire_position_event(DET_DOOR_OPENED, dc); // Even if some of the door is out of LOS, we want the entire // door to be updated. Hitting this case requires a really big // door! if (env.map_knowledge(dc).seen()) { env.map_knowledge(dc).set_feature(grd(dc)); #ifdef USE_TILE env.tile_bk_bg(dc) = tileidx_feature_base(grd(dc)); #endif } if (is_excluded(dc)) excludes.push_back(dc); } update_exclusion_los(excludes); viewwindow(); you.turn_is_over = true; } void player_close_door(coord_def doorpos) { // Finally, close the opened door! string berserk_close = env.markers.property_at(doorpos, MAT_ANY, "door_berserk_verb_close"); const string berserk_adjective = env.markers.property_at(doorpos, MAT_ANY, "door_berserk_adjective"); const string door_close_creak = env.markers.property_at(doorpos, MAT_ANY, "door_noisy_verb_close"); const string door_airborne = env.markers.property_at(doorpos, MAT_ANY, "door_airborne_verb_close"); const string door_close_verb = env.markers.property_at(doorpos, MAT_ANY, "door_verb_close"); const string door_desc_adj = env.markers.property_at(doorpos, MAT_ANY, "door_description_adjective"); const string door_desc_noun = env.markers.property_at(doorpos, MAT_ANY, "door_description_noun"); set<coord_def> all_door; find_connected_identical(doorpos, all_door); const auto door_vec = vector<coord_def>(all_door.begin(), all_door.end()); const char *adj, *noun; get_door_description(all_door.size(), &adj, &noun); const string waynoun_str = make_stringf("%sway", noun); const char *waynoun = waynoun_str.c_str(); if (!door_desc_adj.empty()) adj = door_desc_adj.c_str(); if (!door_desc_noun.empty()) { noun = door_desc_noun.c_str(); waynoun = noun; } for (const coord_def& dc : all_door) { if (monster* mon = monster_at(dc)) { const bool mons_unseen = !you.can_see(*mon); if (mons_unseen || mons_is_object(mon->type)) { mprf("Something is blocking the %s!", waynoun); // No free detection! if (mons_unseen) you.turn_is_over = true; } else mprf("There's a creature in the %s!", waynoun); return; } if (igrd(dc) != NON_ITEM) { if (!has_push_spaces(dc, false, &door_vec)) { mprf("There's something jamming the %s.", waynoun); return; } } // messaging with gateways will be inconsistent if this isn't last if (you.pos() == dc) { mprf("There's a thick-headed creature in the %s!", waynoun); return; } } const int you_old_top_item = igrd(you.pos()); bool items_moved = false; for (const coord_def& dc : all_door) items_moved |= push_items_from(dc, &door_vec); // TODO: if only one thing moved, use that item's name // TODO: handle des-derived strings. (Better yet, find a way to not have // format strings in des...) const char *items_msg = items_moved ? ", pushing everything out of the way" : ""; const int skill = 8 + you.skill_rdiv(SK_STEALTH, 4, 3); if (you.berserk()) { if (silenced(you.pos())) { if (!berserk_close.empty()) { berserk_close += "."; mprf(berserk_close.c_str(), adj, noun); } else mprf("You slam the %s%s shut%s!", adj, noun, items_msg); } else { if (!berserk_close.empty()) { if (!berserk_adjective.empty()) berserk_close += " " + berserk_adjective; else berserk_close += "."; mprf(MSGCH_SOUND, berserk_close.c_str(), adj, noun); } else { mprf(MSGCH_SOUND, "You slam the %s%s shut with a bang%s!", adj, noun, items_msg); } noisy(15, you.pos()); } } else if (one_chance_in(skill) && !silenced(you.pos())) { if (!door_close_creak.empty()) mprf(MSGCH_SOUND, door_close_creak.c_str(), adj, noun); else { mprf(MSGCH_SOUND, "As you close the %s%s%s, it creaks loudly!", adj, noun, items_msg); } noisy(10, you.pos()); } else { if (you.airborne()) { if (!door_airborne.empty()) mprf(door_airborne.c_str(), adj, noun); else mprf("You reach down and close the %s%s%s.", adj, noun, items_msg); } else { if (!door_close_verb.empty()) mprf(door_close_verb.c_str(), adj, noun); else mprf("You close the %s%s%s.", adj, noun, items_msg); } } vector<coord_def> excludes; for (const coord_def& dc : all_door) { // Once opened, formerly runed doors become normal doors. dgn_close_door(dc); set_terrain_changed(dc); dungeon_events.fire_position_event(DET_DOOR_CLOSED, dc); // Even if some of the door is out of LOS once it's closed // (or even if some of it is out of LOS when it's open), we // want the entire door to be updated. if (env.map_knowledge(dc).seen()) { env.map_knowledge(dc).set_feature(grd(dc)); #ifdef USE_TILE env.tile_bk_bg(dc) = tileidx_feature_base(grd(dc)); #endif } if (is_excluded(dc)) excludes.push_back(dc); } update_exclusion_los(excludes); // item pushing may have moved items under the player if (igrd(you.pos()) != you_old_top_item) item_check(); you.turn_is_over = true; } /** * Return a string describing the player's hand(s) taking a given verb. * * @param plural_verb A plural-agreeing verb. ("Smoulders", "are", etc.) * @return A string describing the action. * E.g. "tentacles smoulder", "paw is", etc. */ string player::hands_verb(const string &plural_verb) const { bool plural; const string hand = hand_name(true, &plural); return hand + " " + conjugate_verb(plural_verb, plural); } // Is this a character that would not normally have a preceding space when // it follows a word? static bool _is_end_punct(char c) { switch (c) { case ' ': case '.': case '!': case '?': case ',': case ':': case ';': case ')': return true; } return false; } /** * Return a string describing the player's hand(s) (or equivalent) taking the * given action (verb). * * @param plural_verb The plural-agreeing verb corresponding to the action to * take. E.g., "smoulder", "glow", "gain", etc. * @param object The object or predicate complement of the action, * including any sentence-final punctuation. E.g. ".", * "new energy.", etc. * @return A string describing the player's hands taking the * given action. E.g. "Your tentacle gains new energy." */ string player::hands_act(const string &plural_verb, const string &object) const { const bool space = !object.empty() && !_is_end_punct(object[0]); return "Your " + hands_verb(plural_verb) + (space ? " " : "") + object; } int player::inaccuracy() const { int degree = 0; if (wearing(EQ_AMULET, AMU_INACCURACY)) degree++; if (get_mutation_level(MUT_MISSING_EYE)) degree++; return degree; } /** * Handle effects that occur after the player character stops berserking. */ void player_end_berserk() { // Sometimes berserk leaves us physically drained. // // Chance of passing out: // - mutation gives a large plus in order to try and // avoid the mutation being a "death sentence" to // certain characters. if (one_chance_in(10 + you.get_mutation_level(MUT_BERSERK) * 25)) { // Note the beauty of Trog! They get an extra save that // goes up to 100% at 6 stars of piety. if (have_passive(passive_t::extend_berserk) && x_chance_in_y(you.piety, piety_breakpoint(5))) { mpr("Trog's vigour flows through your veins."); } else { mprf(MSGCH_WARN, "You pass out from exhaustion."); you.increase_duration(DUR_PARALYSIS, roll_dice(1, 4)); you.stop_directly_constricting_all(false); } } if (!you.duration[DUR_PARALYSIS] && !you.petrified()) mprf(MSGCH_WARN, "You are exhausted."); you.berserk_penalty = 0; const int dur = 12 + roll_dice(2, 12); // Slow durations are multiplied by haste_mul (3/2), exhaustion lasts // slightly longer. you.increase_duration(DUR_BERSERK_COOLDOWN, dur * 2); // Don't trigger too many hints mode messages. const bool hints_slow = Hints.hints_events[HINT_YOU_ENCHANTED]; Hints.hints_events[HINT_YOU_ENCHANTED] = false; slow_player(dur); //Un-apply Berserk's +50% Current/Max HP calc_hp(true, false); learned_something_new(HINT_POSTBERSERK); Hints.hints_events[HINT_YOU_ENCHANTED] = hints_slow; you.redraw_quiver = true; // Can throw again. } /** * Does the player have the Sanguine Armour mutation (not suppressed by a form) * while being at a low enough HP (<67%) for its benefits to trigger? * * @return Whether Sanguine Armour should be active. */ bool sanguine_armour_valid() { // why does this need to specify the activity type explicitly? return you.hp <= you.hp_max * 2 / 3 && you.get_mutation_level(MUT_SANGUINE_ARMOUR, mutation_activity_type::FULL); } /// Trigger sanguine armour, updating the duration & messaging as appropriate. void activate_sanguine_armour() { const bool was_active = you.duration[DUR_SANGUINE_ARMOUR]; you.duration[DUR_SANGUINE_ARMOUR] = random_range(60, 100); if (!was_active) { mpr("Your blood congeals into armour."); you.redraw_armour_class = true; } } /** * Refreshes the protective aura around the player after striking with * a weapon of protection. The duration is very short. */ void refresh_weapon_protection() { if (!you.duration[DUR_SPWPN_PROTECTION]) mpr("Your weapon exudes an aura of protection."); you.increase_duration(DUR_SPWPN_PROTECTION, 3 + random2(2), 5); you.redraw_armour_class = true; } // Is the player immune to a particular hex because of their // intrinsic properties? bool player::immune_to_hex(const spell_type hex) const { switch (hex) { case SPELL_PARALYSIS_GAZE: case SPELL_PARALYSE: case SPELL_SLOW: return stasis(); case SPELL_CONFUSE: case SPELL_CONFUSION_GAZE: case SPELL_MASS_CONFUSION: return clarity() || you.duration[DUR_DIVINE_STAMINA] > 0; case SPELL_TELEPORT_OTHER: case SPELL_BLINK_OTHER: case SPELL_BLINK_OTHER_CLOSE: return no_tele(); case SPELL_MESMERISE: case SPELL_AVATAR_SONG: case SPELL_SIREN_SONG: return clarity() || berserk(); case SPELL_CAUSE_FEAR: return clarity() || !(holiness() & MH_NATURAL) || berserk(); case SPELL_PETRIFY: return res_petrify(); case SPELL_PORKALATOR: return is_lifeless_undead(); case SPELL_VIRULENCE: return res_poison() == 3; // don't include the hidden "sleep immunity" duration case SPELL_SLEEP: case SPELL_DREAM_DUST: return !actor::can_sleep(); case SPELL_HIBERNATION: return !can_hibernate(); default: return false; } } // Activate DUR_AGILE. void player::be_agile(int pow) { const bool were_agile = you.duration[DUR_AGILITY] > 0; mprf(MSGCH_DURATION, "You feel %sagile all of a sudden.", were_agile ? "more " : ""); you.increase_duration(DUR_AGILITY, 35 + random2(pow), 80); if (!were_agile) you.redraw_evasion = true; }
; ; Fast background restore ; ; MSX version ; ; $Id: bkrestore.asm,v 1.6 2016/06/21 20:16:35 dom Exp $ ; SECTION code_clib PUBLIC bkrestore PUBLIC _bkrestore EXTERN bkpixeladdress IF FORmsx INCLUDE "msx.def" ELSE INCLUDE "svi.def" ENDIF .bkrestore ._bkrestore ; __FASTCALL__ : sprite ptr in HL push ix ;save callers push hl pop ix ld h,(ix+2) ld l,(ix+3) ld a,(ix+0) ld b,(ix+1) dec a srl a srl a srl a inc a inc a ; INT ((Xsize-1)/8+2) ld (rbytes+1),a .bkrestores push bc push hl call bkpixeladdress pop hl .rbytes ld b,0 .rloop ;ld (de),a ld a,e ; LSB of video memory ptr di out (VDP_CMD),a ld a,d ; MSB of video mem ptr and @00111111 ; masked with "write command" bits or @01000000 ei out (VDP_CMD), a ld a,(ix+4) ; <- current data byte out (VDP_DATA), a ;inc de push hl ; Point to next byte ld hl,8 add hl,de ex de,hl pop hl inc ix djnz rloop inc l pop bc djnz bkrestores pop ix ;restore callers ret
_forktest: 檔案格式 elf32-i386 Disassembly of section .text: 00000000 <main>: printf(1, "fork test OK\n"); } int main(void) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 51 push %ecx e: 83 ec 04 sub $0x4,%esp forktest(); 11: e8 3a 00 00 00 call 50 <forktest> exit(); 16: e8 77 03 00 00 call 392 <exit> 1b: 66 90 xchg %ax,%ax 1d: 66 90 xchg %ax,%ax 1f: 90 nop 00000020 <printf>: #define N 1000 void printf(int fd, char *s, ...) { 20: 55 push %ebp 21: 89 e5 mov %esp,%ebp 23: 53 push %ebx 24: 83 ec 10 sub $0x10,%esp 27: 8b 5d 0c mov 0xc(%ebp),%ebx write(fd, s, strlen(s)); 2a: 53 push %ebx 2b: e8 a0 01 00 00 call 1d0 <strlen> 30: 83 c4 0c add $0xc,%esp 33: 50 push %eax 34: 53 push %ebx 35: ff 75 08 pushl 0x8(%ebp) 38: e8 75 03 00 00 call 3b2 <write> } 3d: 83 c4 10 add $0x10,%esp 40: 8b 5d fc mov -0x4(%ebp),%ebx 43: c9 leave 44: c3 ret 45: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 49: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000050 <forktest>: void forktest(void) { 50: 55 push %ebp 51: 89 e5 mov %esp,%ebp 53: 53 push %ebx int n, pid; printf(1, "fork test\n"); for(n=0; n<N; n++){ 54: 31 db xor %ebx,%ebx write(fd, s, strlen(s)); } void forktest(void) { 56: 83 ec 10 sub $0x10,%esp #define N 1000 void printf(int fd, char *s, ...) { write(fd, s, strlen(s)); 59: 68 44 04 00 00 push $0x444 5e: e8 6d 01 00 00 call 1d0 <strlen> 63: 83 c4 0c add $0xc,%esp 66: 50 push %eax 67: 68 44 04 00 00 push $0x444 6c: 6a 01 push $0x1 6e: e8 3f 03 00 00 call 3b2 <write> 73: 83 c4 10 add $0x10,%esp 76: eb 19 jmp 91 <forktest+0x41> 78: 90 nop 79: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi for(n=0; n<N; n++){ pid = fork(); if(pid < 0) break; if(pid == 0) 80: 0f 84 7c 00 00 00 je 102 <forktest+0xb2> { int n, pid; printf(1, "fork test\n"); for(n=0; n<N; n++){ 86: 83 c3 01 add $0x1,%ebx 89: 81 fb e8 03 00 00 cmp $0x3e8,%ebx 8f: 74 4f je e0 <forktest+0x90> pid = fork(); 91: e8 f4 02 00 00 call 38a <fork> if(pid < 0) 96: 85 c0 test %eax,%eax 98: 79 e6 jns 80 <forktest+0x30> if(n == N){ printf(1, "fork claimed to work N times!\n", N); exit(); } for(; n > 0; n--){ 9a: 85 db test %ebx,%ebx 9c: 74 10 je ae <forktest+0x5e> 9e: 66 90 xchg %ax,%ax if(wait() < 0){ a0: e8 f5 02 00 00 call 39a <wait> a5: 85 c0 test %eax,%eax a7: 78 5e js 107 <forktest+0xb7> if(n == N){ printf(1, "fork claimed to work N times!\n", N); exit(); } for(; n > 0; n--){ a9: 83 eb 01 sub $0x1,%ebx ac: 75 f2 jne a0 <forktest+0x50> printf(1, "wait stopped early\n"); exit(); } } if(wait() != -1){ ae: e8 e7 02 00 00 call 39a <wait> b3: 83 f8 ff cmp $0xffffffff,%eax b6: 75 71 jne 129 <forktest+0xd9> #define N 1000 void printf(int fd, char *s, ...) { write(fd, s, strlen(s)); b8: 83 ec 0c sub $0xc,%esp bb: 68 76 04 00 00 push $0x476 c0: e8 0b 01 00 00 call 1d0 <strlen> c5: 83 c4 0c add $0xc,%esp c8: 50 push %eax c9: 68 76 04 00 00 push $0x476 ce: 6a 01 push $0x1 d0: e8 dd 02 00 00 call 3b2 <write> printf(1, "wait got too many\n"); exit(); } printf(1, "fork test OK\n"); } d5: 8b 5d fc mov -0x4(%ebp),%ebx d8: c9 leave d9: c3 ret da: 8d b6 00 00 00 00 lea 0x0(%esi),%esi #define N 1000 void printf(int fd, char *s, ...) { write(fd, s, strlen(s)); e0: 83 ec 0c sub $0xc,%esp e3: 68 84 04 00 00 push $0x484 e8: e8 e3 00 00 00 call 1d0 <strlen> ed: 83 c4 0c add $0xc,%esp f0: 50 push %eax f1: 68 84 04 00 00 push $0x484 f6: 6a 01 push $0x1 f8: e8 b5 02 00 00 call 3b2 <write> exit(); } if(n == N){ printf(1, "fork claimed to work N times!\n", N); exit(); fd: e8 90 02 00 00 call 392 <exit> for(n=0; n<N; n++){ pid = fork(); if(pid < 0) break; if(pid == 0) exit(); 102: e8 8b 02 00 00 call 392 <exit> #define N 1000 void printf(int fd, char *s, ...) { write(fd, s, strlen(s)); 107: 83 ec 0c sub $0xc,%esp 10a: 68 4f 04 00 00 push $0x44f 10f: e8 bc 00 00 00 call 1d0 <strlen> 114: 83 c4 0c add $0xc,%esp 117: 50 push %eax 118: 68 4f 04 00 00 push $0x44f 11d: 6a 01 push $0x1 11f: e8 8e 02 00 00 call 3b2 <write> } for(; n > 0; n--){ if(wait() < 0){ printf(1, "wait stopped early\n"); exit(); 124: e8 69 02 00 00 call 392 <exit> #define N 1000 void printf(int fd, char *s, ...) { write(fd, s, strlen(s)); 129: 83 ec 0c sub $0xc,%esp 12c: 68 63 04 00 00 push $0x463 131: e8 9a 00 00 00 call 1d0 <strlen> 136: 83 c4 0c add $0xc,%esp 139: 50 push %eax 13a: 68 63 04 00 00 push $0x463 13f: 6a 01 push $0x1 141: e8 6c 02 00 00 call 3b2 <write> } } if(wait() != -1){ printf(1, "wait got too many\n"); exit(); 146: e8 47 02 00 00 call 392 <exit> 14b: 66 90 xchg %ax,%ax 14d: 66 90 xchg %ax,%ax 14f: 90 nop 00000150 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 150: 55 push %ebp 151: 89 e5 mov %esp,%ebp 153: 53 push %ebx 154: 8b 45 08 mov 0x8(%ebp),%eax 157: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 15a: 89 c2 mov %eax,%edx 15c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 160: 83 c1 01 add $0x1,%ecx 163: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 167: 83 c2 01 add $0x1,%edx 16a: 84 db test %bl,%bl 16c: 88 5a ff mov %bl,-0x1(%edx) 16f: 75 ef jne 160 <strcpy+0x10> ; return os; } 171: 5b pop %ebx 172: 5d pop %ebp 173: c3 ret 174: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 17a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000180 <strcmp>: int strcmp(const char *p, const char *q) { 180: 55 push %ebp 181: 89 e5 mov %esp,%ebp 183: 56 push %esi 184: 53 push %ebx 185: 8b 55 08 mov 0x8(%ebp),%edx 188: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) 18b: 0f b6 02 movzbl (%edx),%eax 18e: 0f b6 19 movzbl (%ecx),%ebx 191: 84 c0 test %al,%al 193: 75 1e jne 1b3 <strcmp+0x33> 195: eb 29 jmp 1c0 <strcmp+0x40> 197: 89 f6 mov %esi,%esi 199: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; 1a0: 83 c2 01 add $0x1,%edx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) 1a3: 0f b6 02 movzbl (%edx),%eax p++, q++; 1a6: 8d 71 01 lea 0x1(%ecx),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) 1a9: 0f b6 59 01 movzbl 0x1(%ecx),%ebx 1ad: 84 c0 test %al,%al 1af: 74 0f je 1c0 <strcmp+0x40> 1b1: 89 f1 mov %esi,%ecx 1b3: 38 d8 cmp %bl,%al 1b5: 74 e9 je 1a0 <strcmp+0x20> p++, q++; return (uchar)*p - (uchar)*q; 1b7: 29 d8 sub %ebx,%eax } 1b9: 5b pop %ebx 1ba: 5e pop %esi 1bb: 5d pop %ebp 1bc: c3 ret 1bd: 8d 76 00 lea 0x0(%esi),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) 1c0: 31 c0 xor %eax,%eax p++, q++; return (uchar)*p - (uchar)*q; 1c2: 29 d8 sub %ebx,%eax } 1c4: 5b pop %ebx 1c5: 5e pop %esi 1c6: 5d pop %ebp 1c7: c3 ret 1c8: 90 nop 1c9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 000001d0 <strlen>: uint strlen(char *s) { 1d0: 55 push %ebp 1d1: 89 e5 mov %esp,%ebp 1d3: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 1d6: 80 39 00 cmpb $0x0,(%ecx) 1d9: 74 12 je 1ed <strlen+0x1d> 1db: 31 d2 xor %edx,%edx 1dd: 8d 76 00 lea 0x0(%esi),%esi 1e0: 83 c2 01 add $0x1,%edx 1e3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 1e7: 89 d0 mov %edx,%eax 1e9: 75 f5 jne 1e0 <strlen+0x10> ; return n; } 1eb: 5d pop %ebp 1ec: c3 ret uint strlen(char *s) { int n; for(n = 0; s[n]; n++) 1ed: 31 c0 xor %eax,%eax ; return n; } 1ef: 5d pop %ebp 1f0: c3 ret 1f1: eb 0d jmp 200 <memset> 1f3: 90 nop 1f4: 90 nop 1f5: 90 nop 1f6: 90 nop 1f7: 90 nop 1f8: 90 nop 1f9: 90 nop 1fa: 90 nop 1fb: 90 nop 1fc: 90 nop 1fd: 90 nop 1fe: 90 nop 1ff: 90 nop 00000200 <memset>: void* memset(void *dst, int c, uint n) { 200: 55 push %ebp 201: 89 e5 mov %esp,%ebp 203: 57 push %edi 204: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 207: 8b 4d 10 mov 0x10(%ebp),%ecx 20a: 8b 45 0c mov 0xc(%ebp),%eax 20d: 89 d7 mov %edx,%edi 20f: fc cld 210: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 212: 89 d0 mov %edx,%eax 214: 5f pop %edi 215: 5d pop %ebp 216: c3 ret 217: 89 f6 mov %esi,%esi 219: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000220 <strchr>: char* strchr(const char *s, char c) { 220: 55 push %ebp 221: 89 e5 mov %esp,%ebp 223: 53 push %ebx 224: 8b 45 08 mov 0x8(%ebp),%eax 227: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 22a: 0f b6 10 movzbl (%eax),%edx 22d: 84 d2 test %dl,%dl 22f: 74 1d je 24e <strchr+0x2e> if(*s == c) 231: 38 d3 cmp %dl,%bl 233: 89 d9 mov %ebx,%ecx 235: 75 0d jne 244 <strchr+0x24> 237: eb 17 jmp 250 <strchr+0x30> 239: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 240: 38 ca cmp %cl,%dl 242: 74 0c je 250 <strchr+0x30> } char* strchr(const char *s, char c) { for(; *s; s++) 244: 83 c0 01 add $0x1,%eax 247: 0f b6 10 movzbl (%eax),%edx 24a: 84 d2 test %dl,%dl 24c: 75 f2 jne 240 <strchr+0x20> if(*s == c) return (char*)s; return 0; 24e: 31 c0 xor %eax,%eax } 250: 5b pop %ebx 251: 5d pop %ebp 252: c3 ret 253: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 259: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000260 <gets>: char* gets(char *buf, int max) { 260: 55 push %ebp 261: 89 e5 mov %esp,%ebp 263: 57 push %edi 264: 56 push %esi 265: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 266: 31 f6 xor %esi,%esi cc = read(0, &c, 1); 268: 8d 7d e7 lea -0x19(%ebp),%edi return 0; } char* gets(char *buf, int max) { 26b: 83 ec 1c sub $0x1c,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 26e: eb 29 jmp 299 <gets+0x39> cc = read(0, &c, 1); 270: 83 ec 04 sub $0x4,%esp 273: 6a 01 push $0x1 275: 57 push %edi 276: 6a 00 push $0x0 278: e8 2d 01 00 00 call 3aa <read> if(cc < 1) 27d: 83 c4 10 add $0x10,%esp 280: 85 c0 test %eax,%eax 282: 7e 1d jle 2a1 <gets+0x41> break; buf[i++] = c; 284: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 288: 8b 55 08 mov 0x8(%ebp),%edx 28b: 89 de mov %ebx,%esi if(c == '\n' || c == '\r') 28d: 3c 0a cmp $0xa,%al for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; 28f: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1) if(c == '\n' || c == '\r') 293: 74 1b je 2b0 <gets+0x50> 295: 3c 0d cmp $0xd,%al 297: 74 17 je 2b0 <gets+0x50> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 299: 8d 5e 01 lea 0x1(%esi),%ebx 29c: 3b 5d 0c cmp 0xc(%ebp),%ebx 29f: 7c cf jl 270 <gets+0x10> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 2a1: 8b 45 08 mov 0x8(%ebp),%eax 2a4: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 2a8: 8d 65 f4 lea -0xc(%ebp),%esp 2ab: 5b pop %ebx 2ac: 5e pop %esi 2ad: 5f pop %edi 2ae: 5d pop %ebp 2af: c3 ret break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 2b0: 8b 45 08 mov 0x8(%ebp),%eax gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 2b3: 89 de mov %ebx,%esi break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 2b5: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 2b9: 8d 65 f4 lea -0xc(%ebp),%esp 2bc: 5b pop %ebx 2bd: 5e pop %esi 2be: 5f pop %edi 2bf: 5d pop %ebp 2c0: c3 ret 2c1: eb 0d jmp 2d0 <stat> 2c3: 90 nop 2c4: 90 nop 2c5: 90 nop 2c6: 90 nop 2c7: 90 nop 2c8: 90 nop 2c9: 90 nop 2ca: 90 nop 2cb: 90 nop 2cc: 90 nop 2cd: 90 nop 2ce: 90 nop 2cf: 90 nop 000002d0 <stat>: int stat(char *n, struct stat *st) { 2d0: 55 push %ebp 2d1: 89 e5 mov %esp,%ebp 2d3: 56 push %esi 2d4: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 2d5: 83 ec 08 sub $0x8,%esp 2d8: 6a 00 push $0x0 2da: ff 75 08 pushl 0x8(%ebp) 2dd: e8 f0 00 00 00 call 3d2 <open> if(fd < 0) 2e2: 83 c4 10 add $0x10,%esp 2e5: 85 c0 test %eax,%eax 2e7: 78 27 js 310 <stat+0x40> return -1; r = fstat(fd, st); 2e9: 83 ec 08 sub $0x8,%esp 2ec: ff 75 0c pushl 0xc(%ebp) 2ef: 89 c3 mov %eax,%ebx 2f1: 50 push %eax 2f2: e8 f3 00 00 00 call 3ea <fstat> 2f7: 89 c6 mov %eax,%esi close(fd); 2f9: 89 1c 24 mov %ebx,(%esp) 2fc: e8 b9 00 00 00 call 3ba <close> return r; 301: 83 c4 10 add $0x10,%esp 304: 89 f0 mov %esi,%eax } 306: 8d 65 f8 lea -0x8(%ebp),%esp 309: 5b pop %ebx 30a: 5e pop %esi 30b: 5d pop %ebp 30c: c3 ret 30d: 8d 76 00 lea 0x0(%esi),%esi int fd; int r; fd = open(n, O_RDONLY); if(fd < 0) return -1; 310: b8 ff ff ff ff mov $0xffffffff,%eax 315: eb ef jmp 306 <stat+0x36> 317: 89 f6 mov %esi,%esi 319: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000320 <atoi>: return r; } int atoi(const char *s) { 320: 55 push %ebp 321: 89 e5 mov %esp,%ebp 323: 53 push %ebx 324: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 327: 0f be 11 movsbl (%ecx),%edx 32a: 8d 42 d0 lea -0x30(%edx),%eax 32d: 3c 09 cmp $0x9,%al 32f: b8 00 00 00 00 mov $0x0,%eax 334: 77 1f ja 355 <atoi+0x35> 336: 8d 76 00 lea 0x0(%esi),%esi 339: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 340: 8d 04 80 lea (%eax,%eax,4),%eax 343: 83 c1 01 add $0x1,%ecx 346: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 34a: 0f be 11 movsbl (%ecx),%edx 34d: 8d 5a d0 lea -0x30(%edx),%ebx 350: 80 fb 09 cmp $0x9,%bl 353: 76 eb jbe 340 <atoi+0x20> n = n*10 + *s++ - '0'; return n; } 355: 5b pop %ebx 356: 5d pop %ebp 357: c3 ret 358: 90 nop 359: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000360 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 360: 55 push %ebp 361: 89 e5 mov %esp,%ebp 363: 56 push %esi 364: 53 push %ebx 365: 8b 5d 10 mov 0x10(%ebp),%ebx 368: 8b 45 08 mov 0x8(%ebp),%eax 36b: 8b 75 0c mov 0xc(%ebp),%esi char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 36e: 85 db test %ebx,%ebx 370: 7e 14 jle 386 <memmove+0x26> 372: 31 d2 xor %edx,%edx 374: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 378: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 37c: 88 0c 10 mov %cl,(%eax,%edx,1) 37f: 83 c2 01 add $0x1,%edx { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 382: 39 da cmp %ebx,%edx 384: 75 f2 jne 378 <memmove+0x18> *dst++ = *src++; return vdst; } 386: 5b pop %ebx 387: 5e pop %esi 388: 5d pop %ebp 389: c3 ret 0000038a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 38a: b8 01 00 00 00 mov $0x1,%eax 38f: cd 40 int $0x40 391: c3 ret 00000392 <exit>: SYSCALL(exit) 392: b8 02 00 00 00 mov $0x2,%eax 397: cd 40 int $0x40 399: c3 ret 0000039a <wait>: SYSCALL(wait) 39a: b8 03 00 00 00 mov $0x3,%eax 39f: cd 40 int $0x40 3a1: c3 ret 000003a2 <pipe>: SYSCALL(pipe) 3a2: b8 04 00 00 00 mov $0x4,%eax 3a7: cd 40 int $0x40 3a9: c3 ret 000003aa <read>: SYSCALL(read) 3aa: b8 05 00 00 00 mov $0x5,%eax 3af: cd 40 int $0x40 3b1: c3 ret 000003b2 <write>: SYSCALL(write) 3b2: b8 10 00 00 00 mov $0x10,%eax 3b7: cd 40 int $0x40 3b9: c3 ret 000003ba <close>: SYSCALL(close) 3ba: b8 15 00 00 00 mov $0x15,%eax 3bf: cd 40 int $0x40 3c1: c3 ret 000003c2 <kill>: SYSCALL(kill) 3c2: b8 06 00 00 00 mov $0x6,%eax 3c7: cd 40 int $0x40 3c9: c3 ret 000003ca <exec>: SYSCALL(exec) 3ca: b8 07 00 00 00 mov $0x7,%eax 3cf: cd 40 int $0x40 3d1: c3 ret 000003d2 <open>: SYSCALL(open) 3d2: b8 0f 00 00 00 mov $0xf,%eax 3d7: cd 40 int $0x40 3d9: c3 ret 000003da <mknod>: SYSCALL(mknod) 3da: b8 11 00 00 00 mov $0x11,%eax 3df: cd 40 int $0x40 3e1: c3 ret 000003e2 <unlink>: SYSCALL(unlink) 3e2: b8 12 00 00 00 mov $0x12,%eax 3e7: cd 40 int $0x40 3e9: c3 ret 000003ea <fstat>: SYSCALL(fstat) 3ea: b8 08 00 00 00 mov $0x8,%eax 3ef: cd 40 int $0x40 3f1: c3 ret 000003f2 <link>: SYSCALL(link) 3f2: b8 13 00 00 00 mov $0x13,%eax 3f7: cd 40 int $0x40 3f9: c3 ret 000003fa <mkdir>: SYSCALL(mkdir) 3fa: b8 14 00 00 00 mov $0x14,%eax 3ff: cd 40 int $0x40 401: c3 ret 00000402 <chdir>: SYSCALL(chdir) 402: b8 09 00 00 00 mov $0x9,%eax 407: cd 40 int $0x40 409: c3 ret 0000040a <dup>: SYSCALL(dup) 40a: b8 0a 00 00 00 mov $0xa,%eax 40f: cd 40 int $0x40 411: c3 ret 00000412 <getpid>: SYSCALL(getpid) 412: b8 0b 00 00 00 mov $0xb,%eax 417: cd 40 int $0x40 419: c3 ret 0000041a <sbrk>: SYSCALL(sbrk) 41a: b8 0c 00 00 00 mov $0xc,%eax 41f: cd 40 int $0x40 421: c3 ret 00000422 <sleep>: SYSCALL(sleep) 422: b8 0d 00 00 00 mov $0xd,%eax 427: cd 40 int $0x40 429: c3 ret 0000042a <uptime>: SYSCALL(uptime) 42a: b8 0e 00 00 00 mov $0xe,%eax 42f: cd 40 int $0x40 431: c3 ret 00000432 <cps>: SYSCALL(cps) 432: b8 16 00 00 00 mov $0x16,%eax 437: cd 40 int $0x40 439: c3 ret 0000043a <chpr>: SYSCALL(chpr) 43a: b8 17 00 00 00 mov $0x17,%eax 43f: cd 40 int $0x40 441: c3 ret
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include "binaryop_arm.h" #include <math.h> #if __ARM_NEON #include "neon_mathfun.h" #include <arm_neon.h> #endif // __ARM_NEON namespace ncnn { BinaryOp_arm::BinaryOp_arm() { #if __ARM_NEON support_packing = true; #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC support_fp16_storage = true; #endif #endif // __ARM_NEON #if NCNN_BF16 support_bf16_storage = true; #endif } #if __ARM_NEON // broadcasting rule // https://github.com/Tencent/ncnn/wiki/binaryop-broadcasting template<typename Op> static int binary_op_pack4(const Mat& a, const Mat& b, Mat& c, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; size_t elemsize = a.elemsize; int elempack = a.elempack; int w1 = b.w; int h1 = b.h; int channels1 = b.c; int size1 = w1 * h1; size_t elemsize1 = b.elemsize; int elempack1 = b.elempack; if (a.dims == 3) { if (b.dims == 3) { if (w1 == 1 && h1 == 1 && channels1 == channels) { // special type 1 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const float* ptr = a.channel(q); const float* b0 = b.channel(q); float* outptr = c.channel(q); float32x4_t _b0 = vld1q_f32(b0); for (int i = 0; i < size; i++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _outp = op(_p, _b0); vst1q_f32(outptr, _outp); ptr += 4; outptr += 4; } } return 0; } if (w1 == w && h1 == h && channels1 == 1 && elempack1 == 1) { // special type 2 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const float* ptr = a.channel(q); const float* ptr1 = b; float* outptr = c.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _p1 = vld1q_dup_f32(ptr1); float32x4_t _outp = op(_p, _p1); vst1q_f32(outptr, _outp); ptr += 4; ptr1 += 1; outptr += 4; } } return 0; } if (w == 1 && h == 1 && channels1 == channels) { // special type 3 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const float* a0 = a.channel(q); const float* ptr1 = b.channel(q); float* outptr = c.channel(q); float32x4_t _a0 = vld1q_f32(a0); for (int i = 0; i < size1; i++) { float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_a0, _p1); vst1q_f32(outptr, _outp); ptr1 += 4; outptr += 4; } } return 0; } if (w1 == w && h1 == h && channels == 1 && elempack == 1) { // special type 4 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const float* ptr = a; const float* ptr1 = b.channel(q); float* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float32x4_t _p = vld1q_dup_f32(ptr); float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_p, _p1); vst1q_f32(outptr, _outp); ptr += 1; ptr1 += 4; outptr += 4; } } return 0; } if (w != 1 && w1 == 1 && h1 == h && channels1 == channels) { // special type 5 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const float* ptr = a.channel(q); const float* ptr1 = b.channel(q); float* outptr = c.channel(q); for (int y = 0; y < h; y++) { float32x4_t _p1 = vld1q_f32(ptr1 + y * 4); for (int x = 0; x < w; x++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _outp = op(_p, _p1); vst1q_f32(outptr, _outp); ptr += 4; outptr += 4; } } } return 0; } if (w1 == w && h != 1 && h1 == 1 && channels1 == channels) { // special type 6 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const float* ptr = a.channel(q); const float* ptr1 = b.channel(q); float* outptr = c.channel(q); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _p1 = vld1q_f32(ptr1 + x * 4); float32x4_t _outp = op(_p, _p1); vst1q_f32(outptr, _outp); ptr += 4; outptr += 4; } } } return 0; } if (w1 != 1 && w == 1 && h1 == h && channels1 == channels) { // special type 7 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const float* ptr = a.channel(q); const float* ptr1 = b.channel(q); float* outptr = c.channel(q); for (int y = 0; y < h1; y++) { float32x4_t _p = vld1q_f32(ptr + y * 4); for (int x = 0; x < w1; x++) { float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_p, _p1); vst1q_f32(outptr, _outp); ptr1 += 4; outptr += 4; } } } return 0; } if (w1 == w && h1 != 1 && h == 1 && channels1 == channels) { // special type 8 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const float* ptr = a.channel(q); const float* ptr1 = b.channel(q); float* outptr = c.channel(q); for (int y = 0; y < h1; y++) { for (int x = 0; x < w1; x++) { float32x4_t _p = vld1q_f32(ptr + x * 4); float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_p, _p1); vst1q_f32(outptr, _outp); ptr1 += 4; outptr += 4; } } } return 0; } // type 19 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const float* ptr = a.channel(q); const float* ptr1 = b.channel(q); float* outptr = c.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_p, _p1); vst1q_f32(outptr, _outp); ptr += 4; ptr1 += 4; outptr += 4; } } return 0; } c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 18 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const float* ptr = a.channel(q); const float* ptr1 = b.row(q); float* outptr = c.channel(q); for (int y = 0; y < h; y++) { float32x4_t _b0 = vld1q_f32(ptr1); for (int x = 0; x < w; x++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _outp = op(_p, _b0); vst1q_f32(outptr, _outp); ptr += 4; outptr += 4; } ptr1 += 4; } } return 0; } if (b.dims == 1) { if (b.w == 1 && elempack1 == 1) { // type 16 float32x4_t _b0 = vdupq_n_f32(b[0]); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const float* ptr = a.channel(q); float* outptr = c.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _outp = op(_p, _b0); vst1q_f32(outptr, _outp); ptr += 4; outptr += 4; } } return 0; } // type 17 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const float* ptr = a.channel(q); float32x4_t _b0 = vld1q_f32((const float*)b + q * 4); float* outptr = c.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _outp = op(_p, _b0); vst1q_f32(outptr, _outp); ptr += 4; outptr += 4; } } return 0; } } else if (a.dims == 2) { if (b.dims == 3) { // type 14 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const float* ptr = a.row(q); const float* ptr1 = b.channel(q); float* outptr = c.channel(q); for (int y = 0; y < h1; y++) { float32x4_t _a0 = vld1q_f32(ptr); for (int x = 0; x < w1; x++) { float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_a0, _p1); vst1q_f32(outptr, _outp); ptr1 += 4; outptr += 4; } ptr += 4; } } return 0; } c.create(w, h, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 13 const float* ptr = a; const float* ptr1 = b; float* outptr = c; for (int i = 0; i < size; i++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_p, _p1); vst1q_f32(outptr, _outp); ptr += 4; ptr1 += 4; outptr += 4; } return 0; } if (b.dims == 1) { c.create(w, h, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1 && elempack1 == 1) { // type 11 float32x4_t _b0 = vdupq_n_f32(b[0]); const float* ptr = a; float* outptr = c; for (int i = 0; i < size; i++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _outp = op(_p, _b0); vst1q_f32(outptr, _outp); ptr += 4; outptr += 4; } return 0; } // type 12 const float* ptr = a; const float* ptr1 = b; float* outptr = c; for (int y = 0; y < h; y++) { float32x4_t _b0 = vld1q_f32(ptr1); for (int x = 0; x < w; x++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _outp = op(_p, _b0); vst1q_f32(outptr, _outp); ptr += 4; outptr += 4; } ptr1 += 4; } return 0; } } else if (a.dims == 1) { if (a.w == 1 && elempack == 1) { if (b.dims == 3) { // type 4 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float32x4_t _a0 = vdupq_n_f32(a[0]); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const float* ptr1 = b.channel(q); float* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_a0, _p1); vst1q_f32(outptr, _outp); ptr1 += 4; outptr += 4; } } return 0; } if (b.dims == 2) { // type 3 c.create(w1, h1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float32x4_t _a0 = vdupq_n_f32(a[0]); const float* ptr1 = b; float* outptr = c; for (int i = 0; i < size1; i++) { float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_a0, _p1); vst1q_f32(outptr, _outp); ptr1 += 4; outptr += 4; } return 0; } if (b.dims == 1) { // type 2 c.create(w1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float32x4_t _a0 = vdupq_n_f32(a[0]); const float* ptr1 = b; float* outptr = c; for (int i = 0; i < w1; i++) { float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_a0, _p1); vst1q_f32(outptr, _outp); ptr1 += 4; outptr += 4; } return 0; } } if (b.dims == 3) { // type 9 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { float32x4_t _a0 = vld1q_f32((const float*)a + q * 4); const float* ptr1 = b.channel(q); float* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_a0, _p1); vst1q_f32(outptr, _outp); ptr1 += 4; outptr += 4; } } return 0; } if (b.dims == 2) { // type 8 c.create(w1, h1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; const float* ptr = a; const float* ptr1 = b; float* outptr = c; for (int y = 0; y < h1; y++) { float32x4_t _a0 = vld1q_f32(ptr); for (int x = 0; x < w1; x++) { float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_a0, _p1); vst1q_f32(outptr, _outp); ptr1 += 4; outptr += 4; } ptr += 4; } return 0; } if (b.dims == 1) { c.create(w, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1 && elempack1 == 1) { // type 6 float32x4_t _b0 = vdupq_n_f32(b[0]); const float* ptr = a; float* outptr = c; for (int i = 0; i < w; i++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _outp = op(_p, _b0); vst1q_f32(outptr, _outp); ptr += 4; outptr += 4; } return 0; } // type 7 const float* ptr = a; const float* ptr1 = b; float* outptr = c; for (int i = 0; i < w; i++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _p1 = vld1q_f32(ptr1); float32x4_t _outp = op(_p, _p1); vst1q_f32(outptr, _outp); ptr += 4; ptr1 += 4; outptr += 4; } } } return 0; } template<typename Op> static int binary_op_scalar_inplace_pack4(Mat& a, float b, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; float32x4_t _b = vdupq_n_f32(b); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { float* ptr = a.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vld1q_f32(ptr); _p = op(_p, _b); vst1q_f32(ptr, _p); ptr += 4; } } return 0; } struct binary_op_add_pack4 { float32x4_t operator()(const float32x4_t& x, const float32x4_t& y) const { return vaddq_f32(x, y); } }; struct binary_op_sub_pack4 { float32x4_t operator()(const float32x4_t& x, const float32x4_t& y) const { return vsubq_f32(x, y); } }; struct binary_op_mul_pack4 { float32x4_t operator()(const float32x4_t& x, const float32x4_t& y) const { return vmulq_f32(x, y); } }; struct binary_op_div_pack4 { float32x4_t operator()(const float32x4_t& x, const float32x4_t& y) const #if __aarch64__ { return vdivq_f32(x, y); } #else { return div_ps(x, y); } #endif }; struct binary_op_max_pack4 { float32x4_t operator()(const float32x4_t& x, const float32x4_t& y) const { return vmaxq_f32(x, y); } }; struct binary_op_min_pack4 { float32x4_t operator()(const float32x4_t& x, const float32x4_t& y) const { return vminq_f32(x, y); } }; struct binary_op_pow_pack4 { float32x4_t operator()(const float32x4_t& x, const float32x4_t& y) const { return pow_ps(x, y); } }; struct binary_op_rsub_pack4 { float32x4_t operator()(const float32x4_t& x, const float32x4_t& y) const { return vsubq_f32(y, x); } }; struct binary_op_rdiv_pack4 { float32x4_t operator()(const float32x4_t& x, const float32x4_t& y) const #if __aarch64__ { return vdivq_f32(y, x); } #else { return div_ps(y, x); } #endif }; #endif // __ARM_NEON int BinaryOp_arm::forward(const std::vector<Mat>& bottom_blobs, std::vector<Mat>& top_blobs, const Option& opt) const { int elembits = std::max(bottom_blobs[0].elembits(), bottom_blobs[1].elembits()); #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC if (opt.use_fp16_storage && elembits == 16) return forward_fp16s(bottom_blobs, top_blobs, opt); #endif #if NCNN_BF16 if (opt.use_bf16_storage && elembits == 16) return forward_bf16s(bottom_blobs, top_blobs, opt); #endif const Mat& bottom_blob = bottom_blobs[0]; const Mat& bottom_blob1 = bottom_blobs[1]; Mat& top_blob = top_blobs[0]; #if __ARM_NEON int elempack = bottom_blob.elempack; int elempack1 = bottom_blob1.elempack; if (elempack == 4 || elempack1 == 4) { if (op_type == Operation_ADD) return binary_op_pack4<binary_op_add_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_SUB) return binary_op_pack4<binary_op_sub_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MUL) return binary_op_pack4<binary_op_mul_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_DIV) return binary_op_pack4<binary_op_div_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MAX) return binary_op_pack4<binary_op_max_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MIN) return binary_op_pack4<binary_op_min_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_POW) return binary_op_pack4<binary_op_pow_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RSUB) return binary_op_pack4<binary_op_rsub_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RDIV) return binary_op_pack4<binary_op_rdiv_pack4>(bottom_blob, bottom_blob1, top_blob, opt); } #endif // __ARM_NEON return BinaryOp::forward(bottom_blobs, top_blobs, opt); } int BinaryOp_arm::forward_inplace(Mat& bottom_top_blob, const Option& opt) const { int elembits = bottom_top_blob.elembits(); #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC if (opt.use_fp16_storage && elembits == 16) return forward_inplace_fp16s(bottom_top_blob, opt); #endif #if NCNN_BF16 if (opt.use_bf16_storage && elembits == 16) return forward_inplace_bf16s(bottom_top_blob, opt); #endif #if __ARM_NEON int elempack = bottom_top_blob.elempack; if (elempack == 4) { if (op_type == Operation_ADD) return binary_op_scalar_inplace_pack4<binary_op_add_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_SUB) return binary_op_scalar_inplace_pack4<binary_op_sub_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_MUL) return binary_op_scalar_inplace_pack4<binary_op_mul_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_DIV) return binary_op_scalar_inplace_pack4<binary_op_div_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_MAX) return binary_op_scalar_inplace_pack4<binary_op_max_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_MIN) return binary_op_scalar_inplace_pack4<binary_op_min_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_POW) return binary_op_scalar_inplace_pack4<binary_op_pow_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_RSUB) return binary_op_scalar_inplace_pack4<binary_op_rsub_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_RDIV) return binary_op_scalar_inplace_pack4<binary_op_rdiv_pack4>(bottom_top_blob, b, opt); } #endif // __ARM_NEON return BinaryOp::forward_inplace(bottom_top_blob, opt); } #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC template<typename Op> static int binary_op_pack8_fp16s(const Mat& a, const Mat& b, Mat& c, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; size_t elemsize = a.elemsize; int elempack = a.elempack; int w1 = b.w; int h1 = b.h; int channels1 = b.c; int size1 = w1 * h1; size_t elemsize1 = b.elemsize; int elempack1 = b.elempack; if (a.dims == 3) { if (b.dims == 3) { if (w1 == 1 && h1 == 1 && channels1 == channels) { // special type 1 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); __fp16* outptr = c.channel(q); const __fp16* b0 = b.channel(q); float16x8_t _b0 = vld1q_f16(b0); for (int i = 0; i < size; i++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _outp = op(_p, _b0); vst1q_f16(outptr, _outp); ptr += 8; outptr += 8; } } return 0; } if (w1 == w && h1 == h && channels1 == 1 && elempack1 == 1) { // special type 2 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b; __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _p1 = vdupq_n_f16(*ptr1); float16x8_t _outp = op(_p, _p1); vst1q_f16(outptr, _outp); ptr += 8; ptr1 += 1; outptr += 8; } } return 0; } if (w == 1 && h == 1 && channels1 == channels) { // special type 3 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* a0 = a.channel(q); __fp16* outptr = c.channel(q); const __fp16* ptr1 = b.channel(q); float16x8_t _a0 = vld1q_f16(a0); for (int i = 0; i < size1; i++) { float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_a0, _p1); vst1q_f16(outptr, _outp); ptr1 += 8; outptr += 8; } } return 0; } if (w1 == w && h1 == h && channels == 1 && elempack == 1) { // special type 4 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a; const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float16x8_t _p = vdupq_n_f16(*ptr); float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_p, _p1); vst1q_f16(outptr, _outp); ptr += 1; ptr1 += 8; outptr += 8; } } return 0; } if (w != 1 && w1 == 1 && h1 == h && channels1 == channels) { // special type 5 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h; y++) { float16x8_t _p1 = vld1q_f16(ptr1 + y * 8); for (int x = 0; x < w; x++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _outp = op(_p, _p1); vst1q_f16(outptr, _outp); ptr += 8; outptr += 8; } } } return 0; } if (w1 == w && h != 1 && h1 == 1 && channels1 == channels) { // special type 6 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _p1 = vld1q_f16(ptr1 + x * 8); float16x8_t _outp = op(_p, _p1); vst1q_f16(outptr, _outp); ptr += 8; outptr += 8; } } } return 0; } if (w1 != 1 && w == 1 && h1 == h && channels1 == channels) { // special type 7 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h1; y++) { float16x8_t _p = vld1q_f16(ptr + y * 8); for (int x = 0; x < w1; x++) { float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_p, _p1); vst1q_f16(outptr, _outp); ptr1 += 8; outptr += 8; } } } return 0; } if (w1 == w && h1 != 1 && h == 1 && channels1 == channels) { // special type 8 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h1; y++) { for (int x = 0; x < w1; x++) { float16x8_t _p = vld1q_f16(ptr + x * 8); float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_p, _p1); vst1q_f16(outptr, _outp); ptr1 += 8; outptr += 8; } } } return 0; } // type 19 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_p, _p1); vst1q_f16(outptr, _outp); ptr += 8; ptr1 += 8; outptr += 8; } } return 0; } c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 18 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.row<const __fp16>(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h; y++) { float16x8_t _b0 = vld1q_f16(ptr1); for (int x = 0; x < w; x++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _outp = op(_p, _b0); vst1q_f16(outptr, _outp); ptr += 8; outptr += 8; } ptr1 += 8; } } return 0; } if (b.dims == 1) { if (b.w == 1 && elempack1 == 1) { // type 16 float16x8_t _b0 = vdupq_n_f16(((const __fp16*)b)[0]); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _outp = op(_p, _b0); vst1q_f16(outptr, _outp); ptr += 8; outptr += 8; } } return 0; } // type 17 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); float16x8_t _b0 = vld1q_f16((const __fp16*)b + q * 8); __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _outp = op(_p, _b0); vst1q_f16(outptr, _outp); ptr += 8; outptr += 8; } } return 0; } } else if (a.dims == 2) { if (b.dims == 3) { // type 14 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.row<const __fp16>(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h1; y++) { float16x8_t _a0 = vld1q_f16(ptr); for (int x = 0; x < w1; x++) { float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_a0, _p1); vst1q_f16(outptr, _outp); ptr1 += 8; outptr += 8; } ptr += 8; } } return 0; } c.create(w, h, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 13 const __fp16* ptr = a; const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < size; i++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_p, _p1); vst1q_f16(outptr, _outp); ptr += 8; ptr1 += 8; outptr += 8; } return 0; } if (b.dims == 1) { c.create(w, h, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1 && elempack1 == 1) { // type 11 float16x8_t _b0 = vdupq_n_f16(((const __fp16*)b)[0]); const __fp16* ptr = a; __fp16* outptr = c; for (int i = 0; i < size; i++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _outp = op(_p, _b0); vst1q_f16(outptr, _outp); ptr += 8; outptr += 8; } return 0; } // type 12 const __fp16* ptr = a; const __fp16* ptr1 = b; __fp16* outptr = c; for (int y = 0; y < h; y++) { float16x8_t _b0 = vld1q_f16(ptr1); for (int x = 0; x < w; x++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _outp = op(_p, _b0); vst1q_f16(outptr, _outp); ptr += 8; outptr += 8; } ptr1 += 8; } return 0; } } else if (a.dims == 1) { if (a.w == 1 && elempack == 1) { if (b.dims == 3) { // type 4 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float16x8_t _a0 = vdupq_n_f16(((const __fp16*)a)[0]); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_a0, _p1); vst1q_f16(outptr, _outp); ptr1 += 8; outptr += 8; } } return 0; } if (b.dims == 2) { // type 3 c.create(w1, h1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float16x8_t _a0 = vdupq_n_f16(((const __fp16*)a)[0]); const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < size1; i++) { float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_a0, _p1); vst1q_f16(outptr, _outp); ptr1 += 8; outptr += 8; } return 0; } if (b.dims == 1) { // type 2 c.create(w1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float16x8_t _a0 = vdupq_n_f16(((const __fp16*)a)[0]); const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < w1; i++) { float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_a0, _p1); vst1q_f16(outptr, _outp); ptr1 += 8; outptr += 8; } return 0; } } if (b.dims == 3) { // type 9 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { float16x8_t _a0 = vld1q_f16((const __fp16*)a + q * 8); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_a0, _p1); vst1q_f16(outptr, _outp); ptr1 += 8; outptr += 8; } } return 0; } if (b.dims == 2) { // type 8 c.create(w1, h1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; const __fp16* ptr = a; const __fp16* ptr1 = b; __fp16* outptr = c; for (int y = 0; y < h1; y++) { float16x8_t _a0 = vld1q_f16(ptr); for (int x = 0; x < w1; x++) { float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_a0, _p1); vst1q_f16(outptr, _outp); ptr1 += 8; outptr += 8; } ptr += 8; } return 0; } if (b.dims == 1) { c.create(w, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1 && elempack1 == 1) { // type 6 float16x8_t _b0 = vdupq_n_f16(((const __fp16*)b)[0]); const __fp16* ptr = a; __fp16* outptr = c; for (int i = 0; i < w; i++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _outp = op(_p, _b0); vst1q_f16(outptr, _outp); ptr += 8; outptr += 8; } return 0; } // type 7 const __fp16* ptr = a; const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < w; i++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _p1 = vld1q_f16(ptr1); float16x8_t _outp = op(_p, _p1); vst1q_f16(outptr, _outp); ptr += 8; ptr1 += 8; outptr += 8; } } } return 0; } template<typename Op> static int binary_op_scalar_inplace_pack8_fp16s(Mat& a, float b, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; float16x8_t _b = vdupq_n_f16((__fp16)b); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = a.channel(q); for (int i = 0; i < size; i++) { float16x8_t _p = vld1q_f16(ptr); _p = op(_p, _b); vst1q_f16(ptr, _p); ptr += 8; } } return 0; } struct binary_op_add_pack8_fp16s { float16x8_t operator()(const float16x8_t& x, const float16x8_t& y) const { return vaddq_f16(x, y); } }; struct binary_op_sub_pack8_fp16s { float16x8_t operator()(const float16x8_t& x, const float16x8_t& y) const { return vsubq_f16(x, y); } }; struct binary_op_mul_pack8_fp16s { float16x8_t operator()(const float16x8_t& x, const float16x8_t& y) const { return vmulq_f16(x, y); } }; struct binary_op_div_pack8_fp16s { float16x8_t operator()(const float16x8_t& x, const float16x8_t& y) const { return vdivq_f16(x, y); } }; struct binary_op_max_pack8_fp16s { float16x8_t operator()(const float16x8_t& x, const float16x8_t& y) const { return vmaxq_f16(x, y); } }; struct binary_op_min_pack8_fp16s { float16x8_t operator()(const float16x8_t& x, const float16x8_t& y) const { return vminq_f16(x, y); } }; struct binary_op_pow_pack8_fp16s { float16x8_t operator()(const float16x8_t& x, const float16x8_t& y) const { float16x4_t z_low = vcvt_f16_f32(pow_ps(vcvt_f32_f16(vget_low_f16(x)), vcvt_f32_f16(vget_low_f16(y)))); float16x4_t z_high = vcvt_f16_f32(pow_ps(vcvt_f32_f16(vget_high_f16(x)), vcvt_f32_f16(vget_high_f16(y)))); return vcombine_f16(z_low, z_high); } }; struct binary_op_rsub_pack8_fp16s { float16x8_t operator()(const float16x8_t& x, const float16x8_t& y) const { return vsubq_f16(y, x); } }; struct binary_op_rdiv_pack8_fp16s { float16x8_t operator()(const float16x8_t& x, const float16x8_t& y) const { return vdivq_f16(y, x); } }; template<typename Op> static int binary_op_pack4_fp16s(const Mat& a, const Mat& b, Mat& c, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; size_t elemsize = a.elemsize; int elempack = a.elempack; int w1 = b.w; int h1 = b.h; int channels1 = b.c; int size1 = w1 * h1; size_t elemsize1 = b.elemsize; int elempack1 = b.elempack; if (a.dims == 3) { if (b.dims == 3) { if (w1 == 1 && h1 == 1 && channels1 == channels) { // special type 1 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); __fp16* outptr = c.channel(q); const __fp16* b0 = b.channel(q); float16x4_t _b0 = vld1_f16(b0); for (int i = 0; i < size; i++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _outp = op(_p, _b0); vst1_f16(outptr, _outp); ptr += 4; outptr += 4; } } return 0; } if (w1 == w && h1 == h && channels1 == 1 && elempack1 == 1) { // special type 2 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b; __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _p1 = vdup_n_f16(*ptr1); float16x4_t _outp = op(_p, _p1); vst1_f16(outptr, _outp); ptr += 4; ptr1 += 1; outptr += 4; } } return 0; } if (w == 1 && h == 1 && channels1 == channels) { // special type 3 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* a0 = a.channel(q); __fp16* outptr = c.channel(q); const __fp16* ptr1 = b.channel(q); float16x4_t _a0 = vld1_f16(a0); for (int i = 0; i < size1; i++) { float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_a0, _p1); vst1_f16(outptr, _outp); ptr1 += 4; outptr += 4; } } return 0; } if (w1 == w && h1 == h && channels == 1 && elempack == 1) { // special type 4 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a; const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float16x4_t _p = vdup_n_f16(*ptr); float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_p, _p1); vst1_f16(outptr, _outp); ptr += 1; ptr1 += 4; outptr += 4; } } return 0; } if (w != 1 && w1 == 1 && h1 == h && channels1 == channels) { // special type 5 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h; y++) { float16x4_t _p1 = vld1_f16(ptr1 + y * 4); for (int x = 0; x < w; x++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _outp = op(_p, _p1); vst1_f16(outptr, _outp); ptr += 4; outptr += 4; } } } return 0; } if (w1 == w && h != 1 && h1 == 1 && channels1 == channels) { // special type 6 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _p1 = vld1_f16(ptr1 + x * 4); float16x4_t _outp = op(_p, _p1); vst1_f16(outptr, _outp); ptr += 4; outptr += 4; } } } return 0; } if (w1 != 1 && w == 1 && h1 == h && channels1 == channels) { // special type 7 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h1; y++) { float16x4_t _p = vld1_f16(ptr + y * 4); for (int x = 0; x < w1; x++) { float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_p, _p1); vst1_f16(outptr, _outp); ptr1 += 4; outptr += 4; } } } return 0; } if (w1 == w && h1 != 1 && h == 1 && channels1 == channels) { // special type 8 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h1; y++) { for (int x = 0; x < w1; x++) { float16x4_t _p = vld1_f16(ptr + x * 4); float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_p, _p1); vst1_f16(outptr, _outp); ptr1 += 4; outptr += 4; } } } return 0; } // type 19 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_p, _p1); vst1_f16(outptr, _outp); ptr += 4; ptr1 += 4; outptr += 4; } } return 0; } c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 18 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.row<const __fp16>(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h; y++) { float16x4_t _b0 = vld1_f16(ptr1); for (int x = 0; x < w; x++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _outp = op(_p, _b0); vst1_f16(outptr, _outp); ptr += 4; outptr += 4; } ptr1 += 4; } } return 0; } if (b.dims == 1) { if (b.w == 1 && elempack1 == 1) { // type 16 float16x4_t _b0 = vdup_n_f16(((const __fp16*)b)[0]); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _outp = op(_p, _b0); vst1_f16(outptr, _outp); ptr += 4; outptr += 4; } } return 0; } // type 17 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); float16x4_t _b0 = vld1_f16((const __fp16*)b + q * 4); __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _outp = op(_p, _b0); vst1_f16(outptr, _outp); ptr += 4; outptr += 4; } } return 0; } } else if (a.dims == 2) { if (b.dims == 3) { // type 14 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.row<const __fp16>(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h1; y++) { float16x4_t _a0 = vld1_f16(ptr); for (int x = 0; x < w1; x++) { float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_a0, _p1); vst1_f16(outptr, _outp); ptr1 += 4; outptr += 4; } ptr += 4; } } return 0; } c.create(w, h, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 13 const __fp16* ptr = a; const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < size; i++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_p, _p1); vst1_f16(outptr, _outp); ptr += 4; ptr1 += 4; outptr += 4; } return 0; } if (b.dims == 1) { c.create(w, h, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1 && elempack1 == 1) { // type 11 float16x4_t _b0 = vdup_n_f16(((const __fp16*)b)[0]); const __fp16* ptr = a; __fp16* outptr = c; for (int i = 0; i < size; i++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _outp = op(_p, _b0); vst1_f16(outptr, _outp); ptr += 4; outptr += 4; } return 0; } // type 12 const __fp16* ptr = a; const __fp16* ptr1 = b; __fp16* outptr = c; for (int y = 0; y < h; y++) { float16x4_t _b0 = vld1_f16(ptr1); for (int x = 0; x < w; x++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _outp = op(_p, _b0); vst1_f16(outptr, _outp); ptr += 4; outptr += 4; } ptr1 += 4; } return 0; } } else if (a.dims == 1) { if (a.w == 1 && elempack == 1) { if (b.dims == 3) { // type 4 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float16x4_t _a0 = vdup_n_f16(((const __fp16*)a)[0]); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_a0, _p1); vst1_f16(outptr, _outp); ptr1 += 4; outptr += 4; } } return 0; } if (b.dims == 2) { // type 3 c.create(w1, h1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float16x4_t _a0 = vdup_n_f16(((const __fp16*)a)[0]); const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < size1; i++) { float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_a0, _p1); vst1_f16(outptr, _outp); ptr1 += 4; outptr += 4; } return 0; } if (b.dims == 1) { // type 2 c.create(w1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float16x4_t _a0 = vdup_n_f16(((const __fp16*)a)[0]); const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < w1; i++) { float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_a0, _p1); vst1_f16(outptr, _outp); ptr1 += 4; outptr += 4; } return 0; } } if (b.dims == 3) { // type 9 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { float16x4_t _a0 = vld1_f16((const __fp16*)a + q * 4); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_a0, _p1); vst1_f16(outptr, _outp); ptr1 += 4; outptr += 4; } } return 0; } if (b.dims == 2) { // type 8 c.create(w1, h1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; const __fp16* ptr = a; const __fp16* ptr1 = b; __fp16* outptr = c; for (int y = 0; y < h1; y++) { float16x4_t _a0 = vld1_f16(ptr); for (int x = 0; x < w1; x++) { float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_a0, _p1); vst1_f16(outptr, _outp); ptr1 += 4; outptr += 4; } ptr += 4; } return 0; } if (b.dims == 1) { c.create(w, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1 && elempack1 == 1) { // type 6 float16x4_t _b0 = vdup_n_f16(((const __fp16*)b)[0]); const __fp16* ptr = a; __fp16* outptr = c; for (int i = 0; i < w; i++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _outp = op(_p, _b0); vst1_f16(outptr, _outp); ptr += 4; outptr += 4; } return 0; } // type 7 const __fp16* ptr = a; const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < w; i++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _p1 = vld1_f16(ptr1); float16x4_t _outp = op(_p, _p1); vst1_f16(outptr, _outp); ptr += 4; ptr1 += 4; outptr += 4; } } } return 0; } template<typename Op> static int binary_op_scalar_inplace_pack4_fp16s(Mat& a, float b, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; float16x4_t _b = vdup_n_f16((__fp16)b); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = a.channel(q); for (int i = 0; i < size; i++) { float16x4_t _p = vld1_f16(ptr); _p = op(_p, _b); vst1_f16(ptr, _p); ptr += 4; } } return 0; } struct binary_op_add_pack4_fp16s { float16x4_t operator()(const float16x4_t& x, const float16x4_t& y) const { return vadd_f16(x, y); } }; struct binary_op_sub_pack4_fp16s { float16x4_t operator()(const float16x4_t& x, const float16x4_t& y) const { return vsub_f16(x, y); } }; struct binary_op_mul_pack4_fp16s { float16x4_t operator()(const float16x4_t& x, const float16x4_t& y) const { return vmul_f16(x, y); } }; struct binary_op_div_pack4_fp16s { float16x4_t operator()(const float16x4_t& x, const float16x4_t& y) const { return vdiv_f16(x, y); } }; struct binary_op_max_pack4_fp16s { float16x4_t operator()(const float16x4_t& x, const float16x4_t& y) const { return vmax_f16(x, y); } }; struct binary_op_min_pack4_fp16s { float16x4_t operator()(const float16x4_t& x, const float16x4_t& y) const { return vmin_f16(x, y); } }; struct binary_op_pow_pack4_fp16s { float16x4_t operator()(const float16x4_t& x, const float16x4_t& y) const { return vcvt_f16_f32(pow_ps(vcvt_f32_f16(x), vcvt_f32_f16(y))); } }; struct binary_op_rsub_pack4_fp16s { float16x4_t operator()(const float16x4_t& x, const float16x4_t& y) const { return vsub_f16(y, x); } }; struct binary_op_rdiv_pack4_fp16s { float16x4_t operator()(const float16x4_t& x, const float16x4_t& y) const { return vdiv_f16(y, x); } }; template<typename Op> static int binary_op_fp16s(const Mat& a, const Mat& b, Mat& c, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; size_t elemsize = a.elemsize; int w1 = b.w; int h1 = b.h; int channels1 = b.c; int size1 = w1 * h1; if (a.dims == 3) { if (b.dims == 3) { if (w1 == 1 && h1 == 1 && channels1 == channels) { // special type 1 c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); const __fp16* b0 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { outptr[i] = op(ptr[i], b0[0]); } } return 0; } if (w1 == w && h1 == h && channels1 == 1) { // special type 2 c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b; __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { outptr[i] = op(ptr[i], ptr1[i]); } } return 0; } if (w == 1 && h == 1 && channels1 == channels) { // special type 3 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* a0 = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size1; i++) { outptr[i] = op(a0[0], ptr1[i]); } } return 0; } if (w1 == w && h1 == h && channels == 1) { // special type 4 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a; const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size1; i++) { outptr[i] = op(ptr[i], ptr1[i]); } } return 0; } if (w != 1 && w1 == 1 && h1 == h && channels1 == channels) { // special type 5 c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h; y++) { const __fp16 b0 = ptr1[y]; for (int x = 0; x < w; x++) { outptr[x] = op(ptr[x], b0); } ptr += w; outptr += w; } } return 0; } if (w1 == w && h != 1 && h1 == 1 && channels1 == channels) { // special type 6 c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { outptr[x] = op(ptr[x], ptr1[x]); } ptr += w; outptr += w; } } return 0; } if (w1 != 1 && w == 1 && h1 == h && channels1 == channels) { // special type 7 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h1; y++) { const __fp16 a0 = ptr[y]; for (int x = 0; x < w1; x++) { outptr[x] = op(a0, ptr1[x]); } ptr1 += w1; outptr += w1; } } return 0; } if (w1 == w && h1 != 1 && h == 1 && channels1 == channels) { // special type 8 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h1; y++) { for (int x = 0; x < w1; x++) { outptr[x] = op(ptr[x], ptr1[x]); } ptr1 += w1; outptr += w1; } } return 0; } // type 19 c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { outptr[i] = op(ptr[i], ptr1[i]); } } return 0; } c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 18 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); const __fp16* ptr1 = b.row<const __fp16>(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h; y++) { const __fp16 b0 = ptr1[y]; for (int x = 0; x < w; x++) { outptr[x] = op(ptr[x], b0); } ptr += w; outptr += w; } } return 0; } if (b.dims == 1) { if (b.w == 1) { // type 16 const __fp16 b0 = ((const __fp16*)b)[0]; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { outptr[i] = op(ptr[i], b0); } } return 0; } // type 17 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const __fp16* ptr = a.channel(q); const __fp16 b0 = ((const __fp16*)b)[q]; __fp16* outptr = c.channel(q); for (int i = 0; i < size; i++) { outptr[i] = op(ptr[i], b0); } } return 0; } } else if (a.dims == 2) { if (b.dims == 3) { // type 14 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr = a.row<const __fp16>(q); const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int y = 0; y < h1; y++) { const __fp16 a0 = ptr[y]; for (int x = 0; x < w1; x++) { outptr[x] = op(a0, ptr1[x]); } ptr1 += w1; outptr += w1; } } return 0; } c.create(w, h, elemsize, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 13 const __fp16* ptr = a; const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < size; i++) { outptr[i] = op(ptr[i], ptr1[i]); } return 0; } if (b.dims == 1) { c.create(w, h, elemsize, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1) { // type 11 const __fp16 b0 = ((const __fp16*)b)[0]; const __fp16* ptr = a; __fp16* outptr = c; for (int i = 0; i < size; i++) { outptr[i] = op(ptr[i], b0); } return 0; } // type 12 const __fp16* ptr = a; __fp16* outptr = c; for (int y = 0; y < h; y++) { const __fp16 b0 = ((const __fp16*)b)[y]; for (int x = 0; x < w; x++) { outptr[x] = op(ptr[x], b0); } ptr += w; outptr += w; } return 0; } } else if (a.dims == 1) { if (a.w == 1) { if (b.dims == 3) { // type 4 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; const __fp16 a0 = ((const __fp16*)a)[0]; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size1; i++) { outptr[i] = op(a0, ptr1[i]); } } return 0; } if (b.dims == 2) { // type 3 c.create(w1, h1, elemsize, opt.blob_allocator); if (c.empty()) return -100; const __fp16 a0 = ((const __fp16*)a)[0]; const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < size1; i++) { outptr[i] = op(a0, ptr1[i]); } return 0; } if (b.dims == 1) { // type 2 c.create(w1, elemsize, opt.blob_allocator); if (c.empty()) return -100; const __fp16 a0 = ((const __fp16*)a)[0]; const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < w1; i++) { outptr[i] = op(a0, ptr1[i]); } return 0; } } if (b.dims == 3) { // type 9 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const __fp16 a0 = ((const __fp16*)a)[q]; const __fp16* ptr1 = b.channel(q); __fp16* outptr = c.channel(q); for (int i = 0; i < size1; i++) { outptr[i] = op(a0, ptr1[i]); } } return 0; } if (b.dims == 2) { // type 8 c.create(w1, h1, elemsize, opt.blob_allocator); if (c.empty()) return -100; const __fp16* ptr1 = b; __fp16* outptr = c; for (int y = 0; y < h1; y++) { const __fp16 a0 = ((const __fp16*)a)[y]; for (int x = 0; x < w1; x++) { outptr[x] = op(a0, ptr1[x]); } ptr1 += w1; outptr += w1; } return 0; } if (b.dims == 1) { c.create(w, elemsize, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1) { // type 6 const __fp16 b0 = ((const __fp16*)b)[0]; const __fp16* ptr = a; __fp16* outptr = c; for (int i = 0; i < w; i++) { outptr[i] = op(ptr[i], b0); } return 0; } // type 7 const __fp16* ptr = a; const __fp16* ptr1 = b; __fp16* outptr = c; for (int i = 0; i < w; i++) { outptr[i] = op(ptr[i], ptr1[i]); } } } return 0; } template<typename Op> static int binary_op_scalar_inplace_fp16s(Mat& a, float b, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; __fp16 b16 = (__fp16)b; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = a.channel(q); for (int i = 0; i < size; i++) { ptr[i] = op(ptr[i], b16); } } return 0; } struct binary_op_add_fp16s { __fp16 operator()(const __fp16& x, const __fp16& y) const { return x + y; } }; struct binary_op_sub_fp16s { __fp16 operator()(const __fp16& x, const __fp16& y) const { return x - y; } }; struct binary_op_mul_fp16s { __fp16 operator()(const __fp16& x, const __fp16& y) const { return x * y; } }; struct binary_op_div_fp16s { __fp16 operator()(const __fp16& x, const __fp16& y) const { return x / y; } }; struct binary_op_max_fp16s { __fp16 operator()(const __fp16& x, const __fp16& y) const { return std::max(x, y); } }; struct binary_op_min_fp16s { __fp16 operator()(const __fp16& x, const __fp16& y) const { return std::min(x, y); } }; struct binary_op_pow_fp16s { __fp16 operator()(const __fp16& x, const __fp16& y) const { return (__fp16)pow(x, y); } }; struct binary_op_rsub_fp16s { __fp16 operator()(const __fp16& x, const __fp16& y) const { return y - x; } }; struct binary_op_rdiv_fp16s { __fp16 operator()(const __fp16& x, const __fp16& y) const { return y / x; } }; int BinaryOp_arm::forward_fp16s(const std::vector<Mat>& bottom_blobs, std::vector<Mat>& top_blobs, const Option& opt) const { const Mat& bottom_blob = bottom_blobs[0]; const Mat& bottom_blob1 = bottom_blobs[1]; Mat& top_blob = top_blobs[0]; int elempack = bottom_blob.elempack; int elempack1 = bottom_blob1.elempack; if (elempack == 8 || elempack1 == 8) { if (op_type == Operation_ADD) return binary_op_pack8_fp16s<binary_op_add_pack8_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_SUB) return binary_op_pack8_fp16s<binary_op_sub_pack8_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MUL) return binary_op_pack8_fp16s<binary_op_mul_pack8_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_DIV) return binary_op_pack8_fp16s<binary_op_div_pack8_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MAX) return binary_op_pack8_fp16s<binary_op_max_pack8_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MIN) return binary_op_pack8_fp16s<binary_op_min_pack8_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_POW) return binary_op_pack8_fp16s<binary_op_pow_pack8_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RSUB) return binary_op_pack8_fp16s<binary_op_rsub_pack8_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RDIV) return binary_op_pack8_fp16s<binary_op_rdiv_pack8_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); } if (elempack == 4 || elempack1 == 4) { if (op_type == Operation_ADD) return binary_op_pack4_fp16s<binary_op_add_pack4_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_SUB) return binary_op_pack4_fp16s<binary_op_sub_pack4_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MUL) return binary_op_pack4_fp16s<binary_op_mul_pack4_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_DIV) return binary_op_pack4_fp16s<binary_op_div_pack4_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MAX) return binary_op_pack4_fp16s<binary_op_max_pack4_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MIN) return binary_op_pack4_fp16s<binary_op_min_pack4_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_POW) return binary_op_pack4_fp16s<binary_op_pow_pack4_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RSUB) return binary_op_pack4_fp16s<binary_op_rsub_pack4_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RDIV) return binary_op_pack4_fp16s<binary_op_rdiv_pack4_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); } if (elempack == 1 && elempack1 == 1) { if (op_type == Operation_ADD) return binary_op_fp16s<binary_op_add_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_SUB) return binary_op_fp16s<binary_op_sub_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MUL) return binary_op_fp16s<binary_op_mul_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_DIV) return binary_op_fp16s<binary_op_div_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MAX) return binary_op_fp16s<binary_op_max_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MIN) return binary_op_fp16s<binary_op_min_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_POW) return binary_op_fp16s<binary_op_pow_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RSUB) return binary_op_fp16s<binary_op_rsub_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RDIV) return binary_op_fp16s<binary_op_rdiv_fp16s>(bottom_blob, bottom_blob1, top_blob, opt); } return 0; } int BinaryOp_arm::forward_inplace_fp16s(Mat& bottom_top_blob, const Option& opt) const { int elempack = bottom_top_blob.elempack; if (elempack == 8) { if (op_type == Operation_ADD) return binary_op_scalar_inplace_pack8_fp16s<binary_op_add_pack8_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_SUB) return binary_op_scalar_inplace_pack8_fp16s<binary_op_sub_pack8_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_MUL) return binary_op_scalar_inplace_pack8_fp16s<binary_op_mul_pack8_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_DIV) return binary_op_scalar_inplace_pack8_fp16s<binary_op_div_pack8_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_MAX) return binary_op_scalar_inplace_pack8_fp16s<binary_op_max_pack8_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_MIN) return binary_op_scalar_inplace_pack8_fp16s<binary_op_min_pack8_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_POW) return binary_op_scalar_inplace_pack8_fp16s<binary_op_pow_pack8_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_RSUB) return binary_op_scalar_inplace_pack8_fp16s<binary_op_rsub_pack8_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_RDIV) return binary_op_scalar_inplace_pack8_fp16s<binary_op_rdiv_pack8_fp16s>(bottom_top_blob, b, opt); } if (elempack == 4) { if (op_type == Operation_ADD) return binary_op_scalar_inplace_pack4_fp16s<binary_op_add_pack4_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_SUB) return binary_op_scalar_inplace_pack4_fp16s<binary_op_sub_pack4_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_MUL) return binary_op_scalar_inplace_pack4_fp16s<binary_op_mul_pack4_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_DIV) return binary_op_scalar_inplace_pack4_fp16s<binary_op_div_pack4_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_MAX) return binary_op_scalar_inplace_pack4_fp16s<binary_op_max_pack4_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_MIN) return binary_op_scalar_inplace_pack4_fp16s<binary_op_min_pack4_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_POW) return binary_op_scalar_inplace_pack4_fp16s<binary_op_pow_pack4_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_RSUB) return binary_op_scalar_inplace_pack4_fp16s<binary_op_rsub_pack4_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_RDIV) return binary_op_scalar_inplace_pack4_fp16s<binary_op_rdiv_pack4_fp16s>(bottom_top_blob, b, opt); } if (elempack == 1) { if (op_type == Operation_ADD) return binary_op_scalar_inplace_fp16s<binary_op_add_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_SUB) return binary_op_scalar_inplace_fp16s<binary_op_sub_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_MUL) return binary_op_scalar_inplace_fp16s<binary_op_mul_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_DIV) return binary_op_scalar_inplace_fp16s<binary_op_div_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_MAX) return binary_op_scalar_inplace_fp16s<binary_op_max_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_MIN) return binary_op_scalar_inplace_fp16s<binary_op_min_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_POW) return binary_op_scalar_inplace_fp16s<binary_op_pow_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_RSUB) return binary_op_scalar_inplace_fp16s<binary_op_rsub_fp16s>(bottom_top_blob, b, opt); if (op_type == Operation_RDIV) return binary_op_scalar_inplace_fp16s<binary_op_rdiv_fp16s>(bottom_top_blob, b, opt); } return 0; } #endif // __ARM_FEATURE_FP16_VECTOR_ARITHMETIC #if NCNN_BF16 #if __ARM_NEON template<typename Op> static int binary_op_pack4_bf16s(const Mat& a, const Mat& b, Mat& c, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; size_t elemsize = a.elemsize; int elempack = a.elempack; int w1 = b.w; int h1 = b.h; int channels1 = b.c; int size1 = w1 * h1; size_t elemsize1 = b.elemsize; int elempack1 = b.elempack; if (a.dims == 3) { if (b.dims == 3) { if (w1 == 1 && h1 == 1 && channels1 == channels) { // special type 1 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); unsigned short* outptr = c.channel(q); const unsigned short* b0 = b.channel(q); float32x4_t _b0 = vcvt_f32_bf16(vld1_u16(b0)); for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _outp = op(_p, _b0); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; outptr += 4; } } return 0; } if (w1 == w && h1 == h && channels1 == 1 && elempack1 == 1) { // special type 2 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b; unsigned short* outptr = c.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _p1 = vdupq_n_f32(bfloat16_to_float32(*ptr1)); float32x4_t _outp = op(_p, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; ptr1 += 1; outptr += 4; } } return 0; } if (w == 1 && h == 1 && channels1 == channels) { // special type 3 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* a0 = a.channel(q); unsigned short* outptr = c.channel(q); const unsigned short* ptr1 = b.channel(q); float32x4_t _a0 = vcvt_f32_bf16(vld1_u16(a0)); for (int i = 0; i < size1; i++) { float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_a0, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr1 += 4; outptr += 4; } } return 0; } if (w1 == w && h1 == h && channels == 1 && elempack == 1) { // special type 4 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a; const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float32x4_t _p = vdupq_n_f32(bfloat16_to_float32(*ptr)); float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_p, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 1; ptr1 += 4; outptr += 4; } } return 0; } if (w != 1 && w1 == 1 && h1 == h && channels1 == channels) { // special type 5 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h; y++) { float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1 + y * 4)); for (int x = 0; x < w; x++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _outp = op(_p, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; outptr += 4; } } } return 0; } if (w1 == w && h != 1 && h1 == 1 && channels1 == channels) { // special type 6 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1 + x * 4)); float32x4_t _outp = op(_p, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; outptr += 4; } } } return 0; } if (w1 != 1 && w == 1 && h1 == h && channels1 == channels) { // special type 7 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h1; y++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr + y * 4)); for (int x = 0; x < w1; x++) { float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_p, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr1 += 4; outptr += 4; } } } return 0; } if (w1 == w && h1 != 1 && h == 1 && channels1 == channels) { // special type 8 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h1; y++) { for (int x = 0; x < w1; x++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr + x * 4)); float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_p, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr1 += 4; outptr += 4; } } } return 0; } // type 19 c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_p, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; ptr1 += 4; outptr += 4; } } return 0; } c.create(w, h, channels, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 18 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.row<const unsigned short>(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h; y++) { float32x4_t _b0 = vcvt_f32_bf16(vld1_u16(ptr1)); for (int x = 0; x < w; x++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _outp = op(_p, _b0); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; outptr += 4; } ptr1 += 4; } } return 0; } if (b.dims == 1) { if (b.w == 1 && elempack1 == 1) { // type 16 float32x4_t _b0 = vdupq_n_f32(bfloat16_to_float32(((const unsigned short*)b)[0])); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _outp = op(_p, _b0); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; outptr += 4; } } return 0; } // type 17 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); float32x4_t _b0 = vcvt_f32_bf16(vld1_u16((const unsigned short*)b + q * 4)); unsigned short* outptr = c.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _outp = op(_p, _b0); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; outptr += 4; } } return 0; } } else if (a.dims == 2) { if (b.dims == 3) { // type 14 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a.row<const unsigned short>(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h1; y++) { float32x4_t _a0 = vcvt_f32_bf16(vld1_u16(ptr)); for (int x = 0; x < w1; x++) { float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_a0, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr1 += 4; outptr += 4; } ptr += 4; } } return 0; } c.create(w, h, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 13 const unsigned short* ptr = a; const unsigned short* ptr1 = b; unsigned short* outptr = c; for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_p, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; ptr1 += 4; outptr += 4; } return 0; } if (b.dims == 1) { c.create(w, h, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1 && elempack1 == 1) { // type 11 float32x4_t _b0 = vdupq_n_f32(bfloat16_to_float32(((const unsigned short*)b)[0])); const unsigned short* ptr = a; unsigned short* outptr = c; for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _outp = op(_p, _b0); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; outptr += 4; } return 0; } // type 12 const unsigned short* ptr = a; const unsigned short* ptr1 = b; unsigned short* outptr = c; for (int y = 0; y < h; y++) { float32x4_t _b0 = vcvt_f32_bf16(vld1_u16(ptr1)); for (int x = 0; x < w; x++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _outp = op(_p, _b0); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; outptr += 4; } ptr1 += 4; } return 0; } } else if (a.dims == 1) { if (a.w == 1 && elempack == 1) { if (b.dims == 3) { // type 4 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float32x4_t _a0 = vdupq_n_f32(bfloat16_to_float32(((const unsigned short*)a)[0])); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_a0, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr1 += 4; outptr += 4; } } return 0; } if (b.dims == 2) { // type 3 c.create(w1, h1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float32x4_t _a0 = vdupq_n_f32(bfloat16_to_float32(((const unsigned short*)a)[0])); const unsigned short* ptr1 = b; unsigned short* outptr = c; for (int i = 0; i < size1; i++) { float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_a0, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr1 += 4; outptr += 4; } return 0; } if (b.dims == 1) { // type 2 c.create(w1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; float32x4_t _a0 = vdupq_n_f32(bfloat16_to_float32(((const unsigned short*)a)[0])); const unsigned short* ptr1 = b; unsigned short* outptr = c; for (int i = 0; i < w1; i++) { float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_a0, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr1 += 4; outptr += 4; } return 0; } } if (b.dims == 3) { // type 9 c.create(w1, h1, channels1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { float32x4_t _a0 = vcvt_f32_bf16(vld1_u16((const unsigned short*)a + q * 4)); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size1; i++) { float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_a0, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr1 += 4; outptr += 4; } } return 0; } if (b.dims == 2) { // type 8 c.create(w1, h1, elemsize1, elempack1, opt.blob_allocator); if (c.empty()) return -100; const unsigned short* ptr = a; const unsigned short* ptr1 = b; unsigned short* outptr = c; for (int y = 0; y < h1; y++) { float32x4_t _a0 = vcvt_f32_bf16(vld1_u16(ptr)); for (int x = 0; x < w1; x++) { float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_a0, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr1 += 4; outptr += 4; } ptr += 4; } return 0; } if (b.dims == 1) { c.create(w, elemsize, elempack, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1 && elempack1 == 1) { // type 6 float32x4_t _b0 = vdupq_n_f32(bfloat16_to_float32(((const unsigned short*)b)[0])); const unsigned short* ptr = a; unsigned short* outptr = c; for (int i = 0; i < w; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _outp = op(_p, _b0); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; outptr += 4; } return 0; } // type 7 const unsigned short* ptr = a; const unsigned short* ptr1 = b; unsigned short* outptr = c; for (int i = 0; i < w; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _p1 = vcvt_f32_bf16(vld1_u16(ptr1)); float32x4_t _outp = op(_p, _p1); vst1_u16(outptr, vcvt_bf16_f32(_outp)); ptr += 4; ptr1 += 4; outptr += 4; } } } return 0; } template<typename Op> static int binary_op_scalar_inplace_pack4_bf16s(Mat& a, float b, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; float32x4_t _b = vdupq_n_f32(b); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { unsigned short* ptr = a.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); _p = op(_p, _b); vst1_u16(ptr, vcvt_bf16_f32(_p)); ptr += 4; } } return 0; } #endif // __ARM_NEON template<typename Op> static int binary_op_bf16s(const Mat& a, const Mat& b, Mat& c, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; size_t elemsize = a.elemsize; int w1 = b.w; int h1 = b.h; int channels1 = b.c; int size1 = w1 * h1; if (a.dims == 3) { if (b.dims == 3) { if (w1 == 1 && h1 == 1 && channels1 == channels) { // special type 1 c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* b0 = b.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size; i++) { outptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[i]), bfloat16_to_float32(b0[0]))); } } return 0; } if (w1 == w && h1 == h && channels1 == 1) { // special type 2 c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b; unsigned short* outptr = c.channel(q); for (int i = 0; i < size; i++) { outptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[i]), bfloat16_to_float32(ptr1[i]))); } } return 0; } if (w == 1 && h == 1 && channels1 == channels) { // special type 3 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* a0 = a.channel(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size1; i++) { outptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(a0[0]), bfloat16_to_float32(ptr1[i]))); } } return 0; } if (w1 == w && h1 == h && channels == 1) { // special type 4 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a; const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size1; i++) { outptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[i]), bfloat16_to_float32(ptr1[i]))); } } return 0; } if (w != 1 && w1 == 1 && h1 == h && channels1 == channels) { // special type 5 c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h; y++) { const float b0 = bfloat16_to_float32(ptr1[y]); for (int x = 0; x < w; x++) { outptr[x] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[x]), b0)); } ptr += w; outptr += w; } } return 0; } if (w1 == w && h != 1 && h1 == 1 && channels1 == channels) { // special type 6 c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { outptr[x] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[x]), bfloat16_to_float32(ptr1[x]))); } ptr += w; outptr += w; } } return 0; } if (w1 != 1 && w == 1 && h1 == h && channels1 == channels) { // special type 7 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h1; y++) { const float a0 = bfloat16_to_float32(ptr[y]); for (int x = 0; x < w1; x++) { outptr[x] = float32_to_bfloat16(op(a0, bfloat16_to_float32(ptr1[x]))); } ptr1 += w1; outptr += w1; } } return 0; } if (w1 == w && h1 != 1 && h == 1 && channels1 == channels) { // special type 8 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h1; y++) { for (int x = 0; x < w1; x++) { outptr[x] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[x]), bfloat16_to_float32(ptr1[x]))); } ptr1 += w1; outptr += w1; } } return 0; } // type 19 c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size; i++) { outptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[i]), bfloat16_to_float32(ptr1[i]))); } } return 0; } c.create(w, h, channels, elemsize, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 18 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); const unsigned short* ptr1 = b.row<const unsigned short>(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h; y++) { const float b0 = bfloat16_to_float32(ptr1[y]); for (int x = 0; x < w; x++) { outptr[x] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[x]), b0)); } ptr += w; outptr += w; } } return 0; } if (b.dims == 1) { if (b.w == 1) { // type 16 const float b0 = bfloat16_to_float32(((const unsigned short*)b)[0]); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size; i++) { outptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[i]), b0)); } } return 0; } // type 17 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const unsigned short* ptr = a.channel(q); const float b0 = bfloat16_to_float32(((const unsigned short*)b)[q]); unsigned short* outptr = c.channel(q); for (int i = 0; i < size; i++) { outptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[i]), b0)); } } return 0; } } else if (a.dims == 2) { if (b.dims == 3) { // type 14 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr = a.row<const unsigned short>(q); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int y = 0; y < h1; y++) { const float a0 = bfloat16_to_float32(ptr[y]); for (int x = 0; x < w1; x++) { outptr[x] = float32_to_bfloat16(op(a0, bfloat16_to_float32(ptr1[x]))); } ptr1 += w1; outptr += w1; } } return 0; } c.create(w, h, elemsize, opt.blob_allocator); if (c.empty()) return -100; if (b.dims == 2) { // type 13 const unsigned short* ptr = a; const unsigned short* ptr1 = b; unsigned short* outptr = c; for (int i = 0; i < size; i++) { outptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[i]), bfloat16_to_float32(ptr1[i]))); } return 0; } if (b.dims == 1) { c.create(w, h, elemsize, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1) { // type 11 const float b0 = bfloat16_to_float32(((const unsigned short*)b)[0]); const unsigned short* ptr = a; unsigned short* outptr = c; for (int i = 0; i < size; i++) { outptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[i]), b0)); } return 0; } // type 12 const unsigned short* ptr = a; unsigned short* outptr = c; for (int y = 0; y < h; y++) { const float b0 = bfloat16_to_float32(((const unsigned short*)b)[y]); for (int x = 0; x < w; x++) { outptr[x] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[x]), b0)); } ptr += w; outptr += w; } return 0; } } else if (a.dims == 1) { if (a.w == 1) { if (b.dims == 3) { // type 4 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; const float a0 = bfloat16_to_float32(((const unsigned short*)a)[0]); #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size1; i++) { outptr[i] = float32_to_bfloat16(op(a0, bfloat16_to_float32(ptr1[i]))); } } return 0; } if (b.dims == 2) { // type 3 c.create(w1, h1, elemsize, opt.blob_allocator); if (c.empty()) return -100; const float a0 = bfloat16_to_float32(((const unsigned short*)a)[0]); const unsigned short* ptr1 = b; unsigned short* outptr = c; for (int i = 0; i < size1; i++) { outptr[i] = float32_to_bfloat16(op(a0, bfloat16_to_float32(ptr1[i]))); } return 0; } if (b.dims == 1) { // type 2 c.create(w1, elemsize, opt.blob_allocator); if (c.empty()) return -100; const float a0 = bfloat16_to_float32(((const unsigned short*)a)[0]); const unsigned short* ptr1 = b; unsigned short* outptr = c; for (int i = 0; i < w1; i++) { outptr[i] = float32_to_bfloat16(op(a0, bfloat16_to_float32(ptr1[i]))); } return 0; } } if (b.dims == 3) { // type 9 c.create(w1, h1, channels1, elemsize, opt.blob_allocator); if (c.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels1; q++) { const float a0 = bfloat16_to_float32(((const unsigned short*)a)[q]); const unsigned short* ptr1 = b.channel(q); unsigned short* outptr = c.channel(q); for (int i = 0; i < size1; i++) { outptr[i] = float32_to_bfloat16(op(a0, bfloat16_to_float32(ptr1[i]))); } } return 0; } if (b.dims == 2) { // type 8 c.create(w1, h1, elemsize, opt.blob_allocator); if (c.empty()) return -100; const unsigned short* ptr1 = b; unsigned short* outptr = c; for (int y = 0; y < h1; y++) { const float a0 = bfloat16_to_float32(((const unsigned short*)a)[y]); for (int x = 0; x < w1; x++) { outptr[x] = float32_to_bfloat16(op(a0, bfloat16_to_float32(ptr1[x]))); } ptr1 += w1; outptr += w1; } return 0; } if (b.dims == 1) { c.create(w, elemsize, opt.blob_allocator); if (c.empty()) return -100; if (b.w == 1) { // type 6 const float b0 = bfloat16_to_float32(((const unsigned short*)b)[0]); const unsigned short* ptr = a; unsigned short* outptr = c; for (int i = 0; i < w; i++) { outptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[i]), b0)); } return 0; } // type 7 const unsigned short* ptr = a; const unsigned short* ptr1 = b; unsigned short* outptr = c; for (int i = 0; i < w; i++) { outptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[i]), bfloat16_to_float32(ptr1[i]))); } } } return 0; } template<typename Op> static int binary_op_scalar_inplace_bf16s(Mat& a, float b, const Option& opt) { Op op; int w = a.w; int h = a.h; int channels = a.c; int size = w * h; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { unsigned short* ptr = a.channel(q); for (int i = 0; i < size; i++) { ptr[i] = float32_to_bfloat16(op(bfloat16_to_float32(ptr[i]), b)); } } return 0; } struct binary_op_add { float operator()(const float& x, const float& y) const { return x + y; } }; struct binary_op_sub { float operator()(const float& x, const float& y) const { return x - y; } }; struct binary_op_mul { float operator()(const float& x, const float& y) const { return x * y; } }; struct binary_op_div { float operator()(const float& x, const float& y) const { return x / y; } }; struct binary_op_max { float operator()(const float& x, const float& y) const { return std::max(x, y); } }; struct binary_op_min { float operator()(const float& x, const float& y) const { return std::min(x, y); } }; struct binary_op_pow { float operator()(const float& x, const float& y) const { return (float)pow(x, y); } }; struct binary_op_rsub { float operator()(const float& x, const float& y) const { return y - x; } }; struct binary_op_rdiv { float operator()(const float& x, const float& y) const { return y / x; } }; int BinaryOp_arm::forward_bf16s(const std::vector<Mat>& bottom_blobs, std::vector<Mat>& top_blobs, const Option& opt) const { const Mat& bottom_blob = bottom_blobs[0]; const Mat& bottom_blob1 = bottom_blobs[1]; Mat& top_blob = top_blobs[0]; int elempack = bottom_blob.elempack; int elempack1 = bottom_blob1.elempack; #if __ARM_NEON if (elempack == 4 || elempack1 == 4) { if (op_type == Operation_ADD) return binary_op_pack4_bf16s<binary_op_add_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_SUB) return binary_op_pack4_bf16s<binary_op_sub_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MUL) return binary_op_pack4_bf16s<binary_op_mul_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_DIV) return binary_op_pack4_bf16s<binary_op_div_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MAX) return binary_op_pack4_bf16s<binary_op_max_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MIN) return binary_op_pack4_bf16s<binary_op_min_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_POW) return binary_op_pack4_bf16s<binary_op_pow_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RSUB) return binary_op_pack4_bf16s<binary_op_rsub_pack4>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RDIV) return binary_op_pack4_bf16s<binary_op_rdiv_pack4>(bottom_blob, bottom_blob1, top_blob, opt); } #endif // __ARM_NEON if (elempack == 1 && elempack1 == 1) { if (op_type == Operation_ADD) return binary_op_bf16s<binary_op_add>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_SUB) return binary_op_bf16s<binary_op_sub>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MUL) return binary_op_bf16s<binary_op_mul>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_DIV) return binary_op_bf16s<binary_op_div>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MAX) return binary_op_bf16s<binary_op_max>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_MIN) return binary_op_bf16s<binary_op_min>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_POW) return binary_op_bf16s<binary_op_pow>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RSUB) return binary_op_bf16s<binary_op_rsub>(bottom_blob, bottom_blob1, top_blob, opt); if (op_type == Operation_RDIV) return binary_op_bf16s<binary_op_rdiv>(bottom_blob, bottom_blob1, top_blob, opt); } return 0; } int BinaryOp_arm::forward_inplace_bf16s(Mat& bottom_top_blob, const Option& opt) const { int elempack = bottom_top_blob.elempack; #if __ARM_NEON if (elempack == 4) { if (op_type == Operation_ADD) return binary_op_scalar_inplace_pack4_bf16s<binary_op_add_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_SUB) return binary_op_scalar_inplace_pack4_bf16s<binary_op_sub_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_MUL) return binary_op_scalar_inplace_pack4_bf16s<binary_op_mul_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_DIV) return binary_op_scalar_inplace_pack4_bf16s<binary_op_div_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_MAX) return binary_op_scalar_inplace_pack4_bf16s<binary_op_max_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_MIN) return binary_op_scalar_inplace_pack4_bf16s<binary_op_min_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_POW) return binary_op_scalar_inplace_pack4_bf16s<binary_op_pow_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_RSUB) return binary_op_scalar_inplace_pack4_bf16s<binary_op_rsub_pack4>(bottom_top_blob, b, opt); if (op_type == Operation_RDIV) return binary_op_scalar_inplace_pack4_bf16s<binary_op_rdiv_pack4>(bottom_top_blob, b, opt); } #endif // __ARM_NEON if (elempack == 1) { if (op_type == Operation_ADD) return binary_op_scalar_inplace_bf16s<binary_op_add>(bottom_top_blob, b, opt); if (op_type == Operation_SUB) return binary_op_scalar_inplace_bf16s<binary_op_sub>(bottom_top_blob, b, opt); if (op_type == Operation_MUL) return binary_op_scalar_inplace_bf16s<binary_op_mul>(bottom_top_blob, b, opt); if (op_type == Operation_DIV) return binary_op_scalar_inplace_bf16s<binary_op_div>(bottom_top_blob, b, opt); if (op_type == Operation_MAX) return binary_op_scalar_inplace_bf16s<binary_op_max>(bottom_top_blob, b, opt); if (op_type == Operation_MIN) return binary_op_scalar_inplace_bf16s<binary_op_min>(bottom_top_blob, b, opt); if (op_type == Operation_POW) return binary_op_scalar_inplace_bf16s<binary_op_pow>(bottom_top_blob, b, opt); if (op_type == Operation_RSUB) return binary_op_scalar_inplace_bf16s<binary_op_rsub>(bottom_top_blob, b, opt); if (op_type == Operation_RDIV) return binary_op_scalar_inplace_bf16s<binary_op_rdiv>(bottom_top_blob, b, opt); } return 0; } #endif // NCNN_BF16 } // namespace ncnn
org 0x7c00 bits 16 cpu 8086 jmp short main nop %define kernel_segment 0x0800 %define kernel_offset 0x0000 %macro DefineValue 3 %1 %2 %3 %1.value: equ %3 %endmacro bios_parameter_block: .oem_id: db "FtrDOS " DefineValue .bytes_per_sector, dw, 512 DefineValue .sectors_per_cluster, db, 1 DefineValue .reserved_sectors, dw, 1 DefineValue .number_of_fats, db, 2 DefineValue .root_dir_entries, dw, 224 DefineValue .logical_sectors, dw, 2880 DefineValue .media_descriptor_type, db, 0xF0 DefineValue .sectors_per_fat, dw, 9 DefineValue .sectors_per_track, dw, 18 DefineValue .sides, dw, 2 DefineValue .hidden_sectors, dd, 0 DefineValue .large_sectors, dd, 0 DefineValue .drive_number, db, 0 ; Uninitialized DefineValue .reserved, db, 0 DefineValue .signature, db, 0x29 DefineValue .volume_id, dd, 0x14031412 .volume_label: db "FutureDOS " .system_string: db "FAT12 " first_fat_sector: equ bios_parameter_block.reserved_sectors.value root_dir_sector: equ first_fat_sector + (bios_parameter_block.number_of_fats.value * bios_parameter_block.sectors_per_fat.value) root_sectors: equ (bios_parameter_block.root_dir_entries.value * 32 + bios_parameter_block.bytes_per_sector.value - 1) / bios_parameter_block.bytes_per_sector.value first_data_sector: equ root_dir_sector + root_sectors main: xor ax, ax mov ds, ax mov es, ax mov [bios_parameter_block.drive_number], dl test dl, dl jz .load_kernel ; Not a floppy, get drive information mov ah, 0x08 int 0x13 and cx, 0b111111 mov [bios_parameter_block.sectors_per_track], cx mov dl, dh xor dh, dh inc dx mov [bios_parameter_block.sides], dx .load_kernel: ; First, load the root dir, and search for the kernel entry mov ax, root_dir_sector mov bx, eof call load_sector mov si, eof - 32 mov di, kernel_filename cld cli ; Intentional .find_kernel: add si, 32 mov al, [si] test al, al jz .kernel_not_found cmp al, 0xE5 je .find_kernel push si push di mov cx, 12 rep cmpsb pop di pop si test cx, cx jnz .find_kernel mov ax, [si+26] .load_cluster: push ax add ax, first_data_sector - 2 mov cx, kernel_segment mov es, cx mov bx, [.memory_offset] call load_sector add [.memory_offset], word 512 pop ax ; Cluster push ax ; Get table offset{ax} (cluster * 1.5) mov bx, ax shr bx, 1 add ax, bx ; Sector{ax} (first_fat_sector + table offset{ax} / 512) ; Sector offset{dx} (table offset{dx} % 512) xor dx, dx div word [bios_parameter_block.bytes_per_sector] add ax, first_fat_sector push dx ; Sector offset cmp ax, [.current_fat_sector] je .do_not_load_fat mov [.current_fat_sector], ax mov bx, eof push cs pop es call load_sector .do_not_load_fat: mov si, eof pop dx ; Sector offset add si, dx mov ax, [si] pop dx ; Cluster ; Decode sector ; Each cluster is 3 bytes, but little endian ; ABC DEF is stored as BC FA DE in memory ; converted to BE (how it's stored in registers): ; even = FA BC, odd = DE FA ; to get the actual index, even = remove nybble (AND 0x0FFF), odd = remove first nybble (>> 4) and dl, 1 jz .and_value mov cl, 4 shr ax, cl jmp .end_decoding .and_value: and ax, 0x0FFF .end_decoding: cmp ax, 0xFF8 jnge .load_cluster jmp kernel_segment:kernel_offset .kernel_not_found: mov si, .kernel_not_found_string call print_string call restart .kernel_not_found_string: db "KERNEL.BIN not found!",0x00 .memory_offset: dw kernel_offset .current_fat_sector: dw 0x0000 ; Functions ; Prints a string ; IN: DS:SI = String ; OUT: Nothing print_string: mov ah, 0x0E .print_char_loop: lodsb test al, al jz .end int 0x10 jmp .print_char_loop .end: ret ; Waits for user input and restarts the computer (never returns) ; IN: Nothing ; OUT: Nothing restart: cli mov si, .restart_string call print_string xor ah, ah int 0x16 mov al, 0x02 .check_empty_buffer: and al, 0x20 jz .send_reset_byte in al, 0x64 jmp .check_empty_buffer .send_reset_byte: mov al, 0xFE out 0x64, al ; Should not happen .halt_loop: hlt jmp .halt_loop ; In case of a NMI .restart_string: db 0x0A,0x0D,"Press any key to restart...",0x00 ; Loads a sector. ; IN: AX = LBA Sector, ES:BX = Place to put the data ; OUT: int 0x13, ah 0x02 return data (doesn't return if carry set, or other error) load_sector: ; LBA to CHS xor dx, dx div word [bios_parameter_block.sectors_per_track] inc dl mov cl, dl xor dx, dx div word [bios_parameter_block.sides] mov dh, dl mov ch, al mov ax, (2 << 8) | 1 ; 2: int 13h service number, 1: sectors to read mov dl, [bios_parameter_block.drive_number] int 0x13 jc .disk_error test ah, ah jnz .disk_error cmp al, 1 jne .disk_error ret .disk_error: mov si, .disk_error_string call print_string call restart .disk_error_string: db "Disk error",0x00 ; Other data kernel_filename: db "KERNEL BIN" times 510 - ($ - $$) db 0x00 dw 0xAA55 eof:
; A212698: Main transitions in systems of n particles with spin 3/2. ; 3,24,144,768,3840,18432,86016,393216,1769472,7864320,34603008,150994944,654311424,2818572288,12079595520,51539607552,219043332096,927712935936,3917010173952,16492674416640,69269232549888,290271069732864,1213860837064704,5066549580791808 mov $1,$0 add $1,1 mov $2,4 pow $2,$0 mul $1,$2 mul $1,3
INCLUDE "constants.asm" ; PokemonPicPointers and UnownPicPointers are assumed to start at the same ; address, but in different banks. This is enforced in pokecrystal.link. SECTION "Pic Pointers", ROMX INCLUDE "data/pokemon/pic_pointers.asm" SECTION "Unown Pic Pointers", ROMX INCLUDE "data/pokemon/unown_pic_pointers.asm" SECTION "Trainer Pic Pointers", ROMX INCLUDE "data/trainers/pic_pointers.asm" SECTION "Pics 1", ROMX HoOhFrontpic: INCBIN "gfx/pokemon/ho_oh/front.animated.2bpp.lz" MachampFrontpic: INCBIN "gfx/pokemon/machamp/front.animated.2bpp.lz" NinetalesFrontpic: INCBIN "gfx/pokemon/ninetales/front.animated.2bpp.lz" FeraligatrFrontpic: INCBIN "gfx/pokemon/feraligatr/front.animated.2bpp.lz" NidokingFrontpic: INCBIN "gfx/pokemon/nidoking/front.animated.2bpp.lz" RaikouFrontpic: INCBIN "gfx/pokemon/raikou/front.animated.2bpp.lz" LugiaFrontpic: INCBIN "gfx/pokemon/lugia/front.animated.2bpp.lz" ArticunoFrontpic: INCBIN "gfx/pokemon/articuno/front.animated.2bpp.lz" TaurosFrontpic: INCBIN "gfx/pokemon/tauros/front.animated.2bpp.lz" VenusaurFrontpic: INCBIN "gfx/pokemon/venusaur/front.animated.2bpp.lz" EnteiFrontpic: INCBIN "gfx/pokemon/entei/front.animated.2bpp.lz" SuicuneFrontpic: INCBIN "gfx/pokemon/suicune/front.animated.2bpp.lz" TyphlosionFrontpic: INCBIN "gfx/pokemon/typhlosion/front.animated.2bpp.lz" SECTION "Pics 2", ROMX BlastoiseFrontpic: INCBIN "gfx/pokemon/blastoise/front.animated.2bpp.lz" RapidashFrontpic: INCBIN "gfx/pokemon/rapidash/front.animated.2bpp.lz" MeganiumFrontpic: INCBIN "gfx/pokemon/meganium/front.animated.2bpp.lz" NidoqueenFrontpic: INCBIN "gfx/pokemon/nidoqueen/front.animated.2bpp.lz" HitmonleeFrontpic: INCBIN "gfx/pokemon/hitmonlee/front.animated.2bpp.lz" ScizorFrontpic: INCBIN "gfx/pokemon/scizor/front.animated.2bpp.lz" BeedrillFrontpic: INCBIN "gfx/pokemon/beedrill/front.animated.2bpp.lz" ArcanineFrontpic: INCBIN "gfx/pokemon/arcanine/front.animated.2bpp.lz" TyranitarFrontpic: INCBIN "gfx/pokemon/tyranitar/front.animated.2bpp.lz" MoltresFrontpic: INCBIN "gfx/pokemon/moltres/front.animated.2bpp.lz" ZapdosFrontpic: INCBIN "gfx/pokemon/zapdos/front.animated.2bpp.lz" ArbokFrontpic: INCBIN "gfx/pokemon/arbok/front.animated.2bpp.lz" MewtwoFrontpic: INCBIN "gfx/pokemon/mewtwo/front.animated.2bpp.lz" FearowFrontpic: INCBIN "gfx/pokemon/fearow/front.animated.2bpp.lz" CharizardFrontpic: INCBIN "gfx/pokemon/charizard/front.animated.2bpp.lz" QuilavaFrontpic: INCBIN "gfx/pokemon/quilava/front.animated.2bpp.lz" SECTION "Pics 3", ROMX SteelixFrontpic: INCBIN "gfx/pokemon/steelix/front.animated.2bpp.lz" AlakazamFrontpic: INCBIN "gfx/pokemon/alakazam/front.animated.2bpp.lz" GyaradosFrontpic: INCBIN "gfx/pokemon/gyarados/front.animated.2bpp.lz" KangaskhanFrontpic: INCBIN "gfx/pokemon/kangaskhan/front.animated.2bpp.lz" RhydonFrontpic: INCBIN "gfx/pokemon/rhydon/front.animated.2bpp.lz" GolduckFrontpic: INCBIN "gfx/pokemon/golduck/front.animated.2bpp.lz" RhyhornFrontpic: INCBIN "gfx/pokemon/rhyhorn/front.animated.2bpp.lz" PidgeotFrontpic: INCBIN "gfx/pokemon/pidgeot/front.animated.2bpp.lz" SlowbroFrontpic: INCBIN "gfx/pokemon/slowbro/front.animated.2bpp.lz" ButterfreeFrontpic: INCBIN "gfx/pokemon/butterfree/front.animated.2bpp.lz" WeezingFrontpic: INCBIN "gfx/pokemon/weezing/front.animated.2bpp.lz" CloysterFrontpic: INCBIN "gfx/pokemon/cloyster/front.animated.2bpp.lz" SkarmoryFrontpic: INCBIN "gfx/pokemon/skarmory/front.animated.2bpp.lz" DewgongFrontpic: INCBIN "gfx/pokemon/dewgong/front.animated.2bpp.lz" VictreebelFrontpic: INCBIN "gfx/pokemon/victreebel/front.animated.2bpp.lz" RaichuFrontpic: INCBIN "gfx/pokemon/raichu/front.animated.2bpp.lz" PrimeapeFrontpic: INCBIN "gfx/pokemon/primeape/front.animated.2bpp.lz" OmastarBackpic: INCBIN "gfx/pokemon/omastar/back.2bpp.lz" SECTION "Pics 4", ROMX DodrioFrontpic: INCBIN "gfx/pokemon/dodrio/front.animated.2bpp.lz" SlowkingFrontpic: INCBIN "gfx/pokemon/slowking/front.animated.2bpp.lz" HitmontopFrontpic: INCBIN "gfx/pokemon/hitmontop/front.animated.2bpp.lz" OnixFrontpic: INCBIN "gfx/pokemon/onix/front.animated.2bpp.lz" BlisseyFrontpic: INCBIN "gfx/pokemon/blissey/front.animated.2bpp.lz" MachokeFrontpic: INCBIN "gfx/pokemon/machoke/front.animated.2bpp.lz" DragoniteFrontpic: INCBIN "gfx/pokemon/dragonite/front.animated.2bpp.lz" PoliwrathFrontpic: INCBIN "gfx/pokemon/poliwrath/front.animated.2bpp.lz" ScytherFrontpic: INCBIN "gfx/pokemon/scyther/front.animated.2bpp.lz" AerodactylFrontpic: INCBIN "gfx/pokemon/aerodactyl/front.animated.2bpp.lz" SeakingFrontpic: INCBIN "gfx/pokemon/seaking/front.animated.2bpp.lz" MukFrontpic: INCBIN "gfx/pokemon/muk/front.animated.2bpp.lz" CroconawFrontpic: INCBIN "gfx/pokemon/croconaw/front.animated.2bpp.lz" HypnoFrontpic: INCBIN "gfx/pokemon/hypno/front.animated.2bpp.lz" NidorinoFrontpic: INCBIN "gfx/pokemon/nidorino/front.animated.2bpp.lz" SandslashFrontpic: INCBIN "gfx/pokemon/sandslash/front.animated.2bpp.lz" JolteonFrontpic: INCBIN "gfx/pokemon/jolteon/front.animated.2bpp.lz" DonphanFrontpic: INCBIN "gfx/pokemon/donphan/front.animated.2bpp.lz" PinsirFrontpic: INCBIN "gfx/pokemon/pinsir/front.animated.2bpp.lz" UnownEFrontpic: INCBIN "gfx/pokemon/unown_e/front.animated.2bpp.lz" SECTION "Pics 5", ROMX GolbatFrontpic: INCBIN "gfx/pokemon/golbat/front.animated.2bpp.lz" KinglerFrontpic: INCBIN "gfx/pokemon/kingler/front.animated.2bpp.lz" ExeggcuteFrontpic: INCBIN "gfx/pokemon/exeggcute/front.animated.2bpp.lz" MagcargoFrontpic: INCBIN "gfx/pokemon/magcargo/front.animated.2bpp.lz" PersianFrontpic: INCBIN "gfx/pokemon/persian/front.animated.2bpp.lz" StantlerFrontpic: INCBIN "gfx/pokemon/stantler/front.animated.2bpp.lz" RaticateFrontpic: INCBIN "gfx/pokemon/raticate/front.animated.2bpp.lz" VenomothFrontpic: INCBIN "gfx/pokemon/venomoth/front.animated.2bpp.lz" PolitoedFrontpic: INCBIN "gfx/pokemon/politoed/front.animated.2bpp.lz" ElectabuzzFrontpic: INCBIN "gfx/pokemon/electabuzz/front.animated.2bpp.lz" MantineFrontpic: INCBIN "gfx/pokemon/mantine/front.animated.2bpp.lz" LickitungFrontpic: INCBIN "gfx/pokemon/lickitung/front.animated.2bpp.lz" KingdraFrontpic: INCBIN "gfx/pokemon/kingdra/front.animated.2bpp.lz" CharmeleonFrontpic: INCBIN "gfx/pokemon/charmeleon/front.animated.2bpp.lz" KadabraFrontpic: INCBIN "gfx/pokemon/kadabra/front.animated.2bpp.lz" ExeggutorFrontpic: INCBIN "gfx/pokemon/exeggutor/front.animated.2bpp.lz" GastlyFrontpic: INCBIN "gfx/pokemon/gastly/front.animated.2bpp.lz" AzumarillFrontpic: INCBIN "gfx/pokemon/azumarill/front.animated.2bpp.lz" ParasectFrontpic: INCBIN "gfx/pokemon/parasect/front.animated.2bpp.lz" MrMimeFrontpic: INCBIN "gfx/pokemon/mr__mime/front.animated.2bpp.lz" HeracrossFrontpic: INCBIN "gfx/pokemon/heracross/front.animated.2bpp.lz" SECTION "Pics 6", ROMX AriadosFrontpic: INCBIN "gfx/pokemon/ariados/front.animated.2bpp.lz" NoctowlFrontpic: INCBIN "gfx/pokemon/noctowl/front.animated.2bpp.lz" WartortleFrontpic: INCBIN "gfx/pokemon/wartortle/front.animated.2bpp.lz" LaprasFrontpic: INCBIN "gfx/pokemon/lapras/front.animated.2bpp.lz" GolemFrontpic: INCBIN "gfx/pokemon/golem/front.animated.2bpp.lz" PoliwhirlFrontpic: INCBIN "gfx/pokemon/poliwhirl/front.animated.2bpp.lz" UrsaringFrontpic: INCBIN "gfx/pokemon/ursaring/front.animated.2bpp.lz" HoundoomFrontpic: INCBIN "gfx/pokemon/houndoom/front.animated.2bpp.lz" KabutopsFrontpic: INCBIN "gfx/pokemon/kabutops/front.animated.2bpp.lz" AmpharosFrontpic: INCBIN "gfx/pokemon/ampharos/front.animated.2bpp.lz" NidorinaFrontpic: INCBIN "gfx/pokemon/nidorina/front.animated.2bpp.lz" FlareonFrontpic: INCBIN "gfx/pokemon/flareon/front.animated.2bpp.lz" FarfetchDFrontpic: INCBIN "gfx/pokemon/farfetch_d/front.animated.2bpp.lz" VileplumeFrontpic: INCBIN "gfx/pokemon/vileplume/front.animated.2bpp.lz" BayleefFrontpic: INCBIN "gfx/pokemon/bayleef/front.animated.2bpp.lz" MagmarFrontpic: INCBIN "gfx/pokemon/magmar/front.animated.2bpp.lz" TentacruelFrontpic: INCBIN "gfx/pokemon/tentacruel/front.animated.2bpp.lz" ElekidFrontpic: INCBIN "gfx/pokemon/elekid/front.animated.2bpp.lz" JumpluffFrontpic: INCBIN "gfx/pokemon/jumpluff/front.animated.2bpp.lz" MarowakFrontpic: INCBIN "gfx/pokemon/marowak/front.animated.2bpp.lz" VulpixFrontpic: INCBIN "gfx/pokemon/vulpix/front.animated.2bpp.lz" GligarFrontpic: INCBIN "gfx/pokemon/gligar/front.animated.2bpp.lz" DunsparceFrontpic: INCBIN "gfx/pokemon/dunsparce/front.animated.2bpp.lz" SECTION "Pics 7", ROMX VaporeonFrontpic: INCBIN "gfx/pokemon/vaporeon/front.animated.2bpp.lz" GirafarigFrontpic: INCBIN "gfx/pokemon/girafarig/front.animated.2bpp.lz" DrowzeeFrontpic: INCBIN "gfx/pokemon/drowzee/front.animated.2bpp.lz" SneaselFrontpic: INCBIN "gfx/pokemon/sneasel/front.animated.2bpp.lz" BellossomFrontpic: INCBIN "gfx/pokemon/bellossom/front.animated.2bpp.lz" SnorlaxFrontpic: INCBIN "gfx/pokemon/snorlax/front.animated.2bpp.lz" WigglytuffFrontpic: INCBIN "gfx/pokemon/wigglytuff/front.animated.2bpp.lz" YanmaFrontpic: INCBIN "gfx/pokemon/yanma/front.animated.2bpp.lz" SmeargleFrontpic: INCBIN "gfx/pokemon/smeargle/front.animated.2bpp.lz" ClefableFrontpic: INCBIN "gfx/pokemon/clefable/front.animated.2bpp.lz" PonytaFrontpic: INCBIN "gfx/pokemon/ponyta/front.animated.2bpp.lz" MurkrowFrontpic: INCBIN "gfx/pokemon/murkrow/front.animated.2bpp.lz" GravelerFrontpic: INCBIN "gfx/pokemon/graveler/front.animated.2bpp.lz" StarmieFrontpic: INCBIN "gfx/pokemon/starmie/front.animated.2bpp.lz" PidgeottoFrontpic: INCBIN "gfx/pokemon/pidgeotto/front.animated.2bpp.lz" LedybaFrontpic: INCBIN "gfx/pokemon/ledyba/front.animated.2bpp.lz" GengarFrontpic: INCBIN "gfx/pokemon/gengar/front.animated.2bpp.lz" OmastarFrontpic: INCBIN "gfx/pokemon/omastar/front.animated.2bpp.lz" PiloswineFrontpic: INCBIN "gfx/pokemon/piloswine/front.animated.2bpp.lz" DugtrioFrontpic: INCBIN "gfx/pokemon/dugtrio/front.animated.2bpp.lz" MagnetonFrontpic: INCBIN "gfx/pokemon/magneton/front.animated.2bpp.lz" DragonairFrontpic: INCBIN "gfx/pokemon/dragonair/front.animated.2bpp.lz" ForretressFrontpic: INCBIN "gfx/pokemon/forretress/front.animated.2bpp.lz" TogeticFrontpic: INCBIN "gfx/pokemon/togetic/front.animated.2bpp.lz" KangaskhanBackpic: INCBIN "gfx/pokemon/kangaskhan/back.2bpp.lz" SECTION "Pics 8", ROMX SeelFrontpic: INCBIN "gfx/pokemon/seel/front.animated.2bpp.lz" CrobatFrontpic: INCBIN "gfx/pokemon/crobat/front.animated.2bpp.lz" ChanseyFrontpic: INCBIN "gfx/pokemon/chansey/front.animated.2bpp.lz" TangelaFrontpic: INCBIN "gfx/pokemon/tangela/front.animated.2bpp.lz" SnubbullFrontpic: INCBIN "gfx/pokemon/snubbull/front.animated.2bpp.lz" GranbullFrontpic: INCBIN "gfx/pokemon/granbull/front.animated.2bpp.lz" MiltankFrontpic: INCBIN "gfx/pokemon/miltank/front.animated.2bpp.lz" HaunterFrontpic: INCBIN "gfx/pokemon/haunter/front.animated.2bpp.lz" SunfloraFrontpic: INCBIN "gfx/pokemon/sunflora/front.animated.2bpp.lz" UmbreonFrontpic: INCBIN "gfx/pokemon/umbreon/front.animated.2bpp.lz" ChikoritaFrontpic: INCBIN "gfx/pokemon/chikorita/front.animated.2bpp.lz" GoldeenFrontpic: INCBIN "gfx/pokemon/goldeen/front.animated.2bpp.lz" EspeonFrontpic: INCBIN "gfx/pokemon/espeon/front.animated.2bpp.lz" XatuFrontpic: INCBIN "gfx/pokemon/xatu/front.animated.2bpp.lz" MewFrontpic: INCBIN "gfx/pokemon/mew/front.animated.2bpp.lz" OctilleryFrontpic: INCBIN "gfx/pokemon/octillery/front.animated.2bpp.lz" JynxFrontpic: INCBIN "gfx/pokemon/jynx/front.animated.2bpp.lz" WobbuffetFrontpic: INCBIN "gfx/pokemon/wobbuffet/front.animated.2bpp.lz" DelibirdFrontpic: INCBIN "gfx/pokemon/delibird/front.animated.2bpp.lz" LedianFrontpic: INCBIN "gfx/pokemon/ledian/front.animated.2bpp.lz" GloomFrontpic: INCBIN "gfx/pokemon/gloom/front.animated.2bpp.lz" FlaaffyFrontpic: INCBIN "gfx/pokemon/flaaffy/front.animated.2bpp.lz" IvysaurFrontpic: INCBIN "gfx/pokemon/ivysaur/front.animated.2bpp.lz" FurretFrontpic: INCBIN "gfx/pokemon/furret/front.animated.2bpp.lz" CyndaquilFrontpic: INCBIN "gfx/pokemon/cyndaquil/front.animated.2bpp.lz" HitmonchanFrontpic: INCBIN "gfx/pokemon/hitmonchan/front.animated.2bpp.lz" QuagsireFrontpic: INCBIN "gfx/pokemon/quagsire/front.animated.2bpp.lz" SECTION "Pics 9", ROMX EkansFrontpic: INCBIN "gfx/pokemon/ekans/front.animated.2bpp.lz" SudowoodoFrontpic: INCBIN "gfx/pokemon/sudowoodo/front.animated.2bpp.lz" PikachuFrontpic: INCBIN "gfx/pokemon/pikachu/front.animated.2bpp.lz" SeadraFrontpic: INCBIN "gfx/pokemon/seadra/front.animated.2bpp.lz" MagbyFrontpic: INCBIN "gfx/pokemon/magby/front.animated.2bpp.lz" WeepinbellFrontpic: INCBIN "gfx/pokemon/weepinbell/front.animated.2bpp.lz" TotodileFrontpic: INCBIN "gfx/pokemon/totodile/front.animated.2bpp.lz" CorsolaFrontpic: INCBIN "gfx/pokemon/corsola/front.animated.2bpp.lz" FirebreatherPic: INCBIN "gfx/trainers/firebreather.2bpp.lz" MachopFrontpic: INCBIN "gfx/pokemon/machop/front.animated.2bpp.lz" ChinchouFrontpic: INCBIN "gfx/pokemon/chinchou/front.animated.2bpp.lz" RattataFrontpic: INCBIN "gfx/pokemon/rattata/front.animated.2bpp.lz" ChampionPic: INCBIN "gfx/trainers/champion.2bpp.lz" SpearowFrontpic: INCBIN "gfx/pokemon/spearow/front.animated.2bpp.lz" MagikarpFrontpic: INCBIN "gfx/pokemon/magikarp/front.animated.2bpp.lz" CharmanderFrontpic: INCBIN "gfx/pokemon/charmander/front.animated.2bpp.lz" CuboneFrontpic: INCBIN "gfx/pokemon/cubone/front.animated.2bpp.lz" BlackbeltTPic: INCBIN "gfx/trainers/blackbelt_t.2bpp.lz" BikerPic: INCBIN "gfx/trainers/biker.2bpp.lz" NidoranMFrontpic: INCBIN "gfx/pokemon/nidoran_m/front.animated.2bpp.lz" PorygonFrontpic: INCBIN "gfx/pokemon/porygon/front.animated.2bpp.lz" BrunoPic: INCBIN "gfx/trainers/bruno.2bpp.lz" GrimerFrontpic: INCBIN "gfx/pokemon/grimer/front.animated.2bpp.lz" StaryuFrontpic: INCBIN "gfx/pokemon/staryu/front.animated.2bpp.lz" HikerPic: INCBIN "gfx/trainers/hiker.2bpp.lz" MeowthFrontpic: INCBIN "gfx/pokemon/meowth/front.animated.2bpp.lz" Porygon2Frontpic: INCBIN "gfx/pokemon/porygon2/front.animated.2bpp.lz" SandshrewFrontpic: INCBIN "gfx/pokemon/sandshrew/front.animated.2bpp.lz" NidoranFFrontpic: INCBIN "gfx/pokemon/nidoran_f/front.animated.2bpp.lz" PidgeyFrontpic: INCBIN "gfx/pokemon/pidgey/front.animated.2bpp.lz" ParasectBackpic: INCBIN "gfx/pokemon/parasect/back.2bpp.lz" SECTION "Pics 10", ROMX MisdreavusFrontpic: INCBIN "gfx/pokemon/misdreavus/front.animated.2bpp.lz" HoundourFrontpic: INCBIN "gfx/pokemon/houndour/front.animated.2bpp.lz" MankeyFrontpic: INCBIN "gfx/pokemon/mankey/front.animated.2bpp.lz" CelebiFrontpic: INCBIN "gfx/pokemon/celebi/front.animated.2bpp.lz" MediumPic: INCBIN "gfx/trainers/medium.2bpp.lz" PinecoFrontpic: INCBIN "gfx/pokemon/pineco/front.animated.2bpp.lz" KrabbyFrontpic: INCBIN "gfx/pokemon/krabby/front.animated.2bpp.lz" FisherPic: INCBIN "gfx/trainers/fisher.2bpp.lz" JigglypuffFrontpic: INCBIN "gfx/pokemon/jigglypuff/front.animated.2bpp.lz" ParasFrontpic: INCBIN "gfx/pokemon/paras/front.animated.2bpp.lz" NidokingBackpic: INCBIN "gfx/pokemon/nidoking/back.2bpp.lz" PokefanmPic: INCBIN "gfx/trainers/pokefan_m.2bpp.lz" BoarderPic: INCBIN "gfx/trainers/boarder.2bpp.lz" PsyduckFrontpic: INCBIN "gfx/pokemon/psyduck/front.animated.2bpp.lz" SquirtleFrontpic: INCBIN "gfx/pokemon/squirtle/front.animated.2bpp.lz" MachampBackpic: INCBIN "gfx/pokemon/machamp/back.2bpp.lz" KoffingFrontpic: INCBIN "gfx/pokemon/koffing/front.animated.2bpp.lz" VenonatFrontpic: INCBIN "gfx/pokemon/venonat/front.animated.2bpp.lz" ExeggutorBackpic: INCBIN "gfx/pokemon/exeggutor/back.2bpp.lz" LanturnFrontpic: INCBIN "gfx/pokemon/lanturn/front.animated.2bpp.lz" TyrogueFrontpic: INCBIN "gfx/pokemon/tyrogue/front.animated.2bpp.lz" SkiploomFrontpic: INCBIN "gfx/pokemon/skiploom/front.animated.2bpp.lz" MareepFrontpic: INCBIN "gfx/pokemon/mareep/front.animated.2bpp.lz" ChuckPic: INCBIN "gfx/trainers/chuck.2bpp.lz" EeveeFrontpic: INCBIN "gfx/pokemon/eevee/front.animated.2bpp.lz" ButterfreeBackpic: INCBIN "gfx/pokemon/butterfree/back.2bpp.lz" ZubatFrontpic: INCBIN "gfx/pokemon/zubat/front.animated.2bpp.lz" KimonoGirlPic: INCBIN "gfx/trainers/kimono_girl.2bpp.lz" AlakazamBackpic: INCBIN "gfx/pokemon/alakazam/back.2bpp.lz" AipomFrontpic: INCBIN "gfx/pokemon/aipom/front.animated.2bpp.lz" AbraFrontpic: INCBIN "gfx/pokemon/abra/front.animated.2bpp.lz" HitmontopBackpic: INCBIN "gfx/pokemon/hitmontop/back.2bpp.lz" CloysterBackpic: INCBIN "gfx/pokemon/cloyster/back.2bpp.lz" HoothootFrontpic: INCBIN "gfx/pokemon/hoothoot/front.animated.2bpp.lz" UnownFBackpic: INCBIN "gfx/pokemon/unown_f/back.2bpp.lz" SECTION "Pics 11", ROMX DodrioBackpic: INCBIN "gfx/pokemon/dodrio/back.2bpp.lz" ClefairyFrontpic: INCBIN "gfx/pokemon/clefairy/front.animated.2bpp.lz" SlugmaFrontpic: INCBIN "gfx/pokemon/slugma/front.animated.2bpp.lz" GrowlitheFrontpic: INCBIN "gfx/pokemon/growlithe/front.animated.2bpp.lz" SlowpokeFrontpic: INCBIN "gfx/pokemon/slowpoke/front.animated.2bpp.lz" SmoochumFrontpic: INCBIN "gfx/pokemon/smoochum/front.animated.2bpp.lz" JugglerPic: INCBIN "gfx/trainers/juggler.2bpp.lz" MarillFrontpic: INCBIN "gfx/pokemon/marill/front.animated.2bpp.lz" GuitaristPic: INCBIN "gfx/trainers/guitarist.2bpp.lz" PokefanfPic: INCBIN "gfx/trainers/pokefan_f.2bpp.lz" VenomothBackpic: INCBIN "gfx/pokemon/venomoth/back.2bpp.lz" ClairPic: INCBIN "gfx/trainers/clair.2bpp.lz" PokemaniacPic: INCBIN "gfx/trainers/pokemaniac.2bpp.lz" OmanyteFrontpic: INCBIN "gfx/pokemon/omanyte/front.animated.2bpp.lz" SkierPic: INCBIN "gfx/trainers/skier.2bpp.lz" PupitarFrontpic: INCBIN "gfx/pokemon/pupitar/front.animated.2bpp.lz" BellsproutFrontpic: INCBIN "gfx/pokemon/bellsprout/front.animated.2bpp.lz" ShellderFrontpic: INCBIN "gfx/pokemon/shellder/front.animated.2bpp.lz" TentacoolFrontpic: INCBIN "gfx/pokemon/tentacool/front.animated.2bpp.lz" CleffaFrontpic: INCBIN "gfx/pokemon/cleffa/front.animated.2bpp.lz" GyaradosBackpic: INCBIN "gfx/pokemon/gyarados/back.2bpp.lz" NinetalesBackpic: INCBIN "gfx/pokemon/ninetales/back.2bpp.lz" YanmaBackpic: INCBIN "gfx/pokemon/yanma/back.2bpp.lz" PinsirBackpic: INCBIN "gfx/pokemon/pinsir/back.2bpp.lz" LassPic: INCBIN "gfx/trainers/lass.2bpp.lz" ClefableBackpic: INCBIN "gfx/pokemon/clefable/back.2bpp.lz" DoduoFrontpic: INCBIN "gfx/pokemon/doduo/front.animated.2bpp.lz" FeraligatrBackpic: INCBIN "gfx/pokemon/feraligatr/back.2bpp.lz" DratiniFrontpic: INCBIN "gfx/pokemon/dratini/front.animated.2bpp.lz" MagnetonBackpic: INCBIN "gfx/pokemon/magneton/back.2bpp.lz" QwilfishFrontpic: INCBIN "gfx/pokemon/qwilfish/front.animated.2bpp.lz" SuicuneBackpic: INCBIN "gfx/pokemon/suicune/back.2bpp.lz" SlowkingBackpic: INCBIN "gfx/pokemon/slowking/back.2bpp.lz" ElekidBackpic: INCBIN "gfx/pokemon/elekid/back.2bpp.lz" CelebiBackpic: INCBIN "gfx/pokemon/celebi/back.2bpp.lz" KrabbyBackpic: INCBIN "gfx/pokemon/krabby/back.2bpp.lz" BugCatcherPic: INCBIN "gfx/trainers/bug_catcher.2bpp.lz" SnorlaxBackpic: INCBIN "gfx/pokemon/snorlax/back.2bpp.lz" SECTION "Pics 12", ROMX VenusaurBackpic: INCBIN "gfx/pokemon/venusaur/back.2bpp.lz" MoltresBackpic: INCBIN "gfx/pokemon/moltres/back.2bpp.lz" SunfloraBackpic: INCBIN "gfx/pokemon/sunflora/back.2bpp.lz" PhanpyFrontpic: INCBIN "gfx/pokemon/phanpy/front.animated.2bpp.lz" RhydonBackpic: INCBIN "gfx/pokemon/rhydon/back.2bpp.lz" LarvitarFrontpic: INCBIN "gfx/pokemon/larvitar/front.animated.2bpp.lz" TyranitarBackpic: INCBIN "gfx/pokemon/tyranitar/back.2bpp.lz" SandslashBackpic: INCBIN "gfx/pokemon/sandslash/back.2bpp.lz" SeadraBackpic: INCBIN "gfx/pokemon/seadra/back.2bpp.lz" TwinsPic: INCBIN "gfx/trainers/twins.2bpp.lz" FarfetchDBackpic: INCBIN "gfx/pokemon/farfetch_d/back.2bpp.lz" NidoranMBackpic: INCBIN "gfx/pokemon/nidoran_m/back.2bpp.lz" LedybaBackpic: INCBIN "gfx/pokemon/ledyba/back.2bpp.lz" CyndaquilBackpic: INCBIN "gfx/pokemon/cyndaquil/back.2bpp.lz" BayleefBackpic: INCBIN "gfx/pokemon/bayleef/back.2bpp.lz" OddishFrontpic: INCBIN "gfx/pokemon/oddish/front.animated.2bpp.lz" RapidashBackpic: INCBIN "gfx/pokemon/rapidash/back.2bpp.lz" DoduoBackpic: INCBIN "gfx/pokemon/doduo/back.2bpp.lz" HoppipFrontpic: INCBIN "gfx/pokemon/hoppip/front.animated.2bpp.lz" MankeyBackpic: INCBIN "gfx/pokemon/mankey/back.2bpp.lz" MagmarBackpic: INCBIN "gfx/pokemon/magmar/back.2bpp.lz" HypnoBackpic: INCBIN "gfx/pokemon/hypno/back.2bpp.lz" QuilavaBackpic: INCBIN "gfx/pokemon/quilava/back.2bpp.lz" CroconawBackpic: INCBIN "gfx/pokemon/croconaw/back.2bpp.lz" SandshrewBackpic: INCBIN "gfx/pokemon/sandshrew/back.2bpp.lz" SailorPic: INCBIN "gfx/trainers/sailor.2bpp.lz" BeautyPic: INCBIN "gfx/trainers/beauty.2bpp.lz" ShellderBackpic: INCBIN "gfx/pokemon/shellder/back.2bpp.lz" ZubatBackpic: INCBIN "gfx/pokemon/zubat/back.2bpp.lz" TeddiursaFrontpic: INCBIN "gfx/pokemon/teddiursa/front.animated.2bpp.lz" CuboneBackpic: INCBIN "gfx/pokemon/cubone/back.2bpp.lz" GruntmPic: INCBIN "gfx/trainers/grunt_m.2bpp.lz" GloomBackpic: INCBIN "gfx/pokemon/gloom/back.2bpp.lz" MagcargoBackpic: INCBIN "gfx/pokemon/magcargo/back.2bpp.lz" KabutopsBackpic: INCBIN "gfx/pokemon/kabutops/back.2bpp.lz" BeedrillBackpic: INCBIN "gfx/pokemon/beedrill/back.2bpp.lz" ArcanineBackpic: INCBIN "gfx/pokemon/arcanine/back.2bpp.lz" FlareonBackpic: INCBIN "gfx/pokemon/flareon/back.2bpp.lz" GoldeenBackpic: INCBIN "gfx/pokemon/goldeen/back.2bpp.lz" BulbasaurFrontpic: INCBIN "gfx/pokemon/bulbasaur/front.animated.2bpp.lz" StarmieBackpic: INCBIN "gfx/pokemon/starmie/back.2bpp.lz" SECTION "Pics 13", ROMX OmanyteBackpic: INCBIN "gfx/pokemon/omanyte/back.2bpp.lz" PidgeyBackpic: INCBIN "gfx/pokemon/pidgey/back.2bpp.lz" ScientistPic: INCBIN "gfx/trainers/scientist.2bpp.lz" QwilfishBackpic: INCBIN "gfx/pokemon/qwilfish/back.2bpp.lz" GligarBackpic: INCBIN "gfx/pokemon/gligar/back.2bpp.lz" TyphlosionBackpic: INCBIN "gfx/pokemon/typhlosion/back.2bpp.lz" CharmeleonBackpic: INCBIN "gfx/pokemon/charmeleon/back.2bpp.lz" NidoqueenBackpic: INCBIN "gfx/pokemon/nidoqueen/back.2bpp.lz" PichuFrontpic: INCBIN "gfx/pokemon/pichu/front.animated.2bpp.lz" ElectabuzzBackpic: INCBIN "gfx/pokemon/electabuzz/back.2bpp.lz" LedianBackpic: INCBIN "gfx/pokemon/ledian/back.2bpp.lz" PupitarBackpic: INCBIN "gfx/pokemon/pupitar/back.2bpp.lz" HeracrossBackpic: INCBIN "gfx/pokemon/heracross/back.2bpp.lz" UnownDFrontpic: INCBIN "gfx/pokemon/unown_d/front.animated.2bpp.lz" MiltankBackpic: INCBIN "gfx/pokemon/miltank/back.2bpp.lz" SteelixBackpic: INCBIN "gfx/pokemon/steelix/back.2bpp.lz" PersianBackpic: INCBIN "gfx/pokemon/persian/back.2bpp.lz" LtSurgePic: INCBIN "gfx/trainers/lt_surge.2bpp.lz" TeacherPic: INCBIN "gfx/trainers/teacher.2bpp.lz" EggPic: INCBIN "gfx/pokemon/egg/front.animated.2bpp.lz" EeveeBackpic: INCBIN "gfx/pokemon/eevee/back.2bpp.lz" ShuckleFrontpic: INCBIN "gfx/pokemon/shuckle/front.animated.2bpp.lz" PonytaBackpic: INCBIN "gfx/pokemon/ponyta/back.2bpp.lz" RemoraidFrontpic: INCBIN "gfx/pokemon/remoraid/front.animated.2bpp.lz" PoliwagFrontpic: INCBIN "gfx/pokemon/poliwag/front.animated.2bpp.lz" OnixBackpic: INCBIN "gfx/pokemon/onix/back.2bpp.lz" KoffingBackpic: INCBIN "gfx/pokemon/koffing/back.2bpp.lz" BirdKeeperPic: INCBIN "gfx/trainers/bird_keeper.2bpp.lz" FalknerPic: INCBIN "gfx/trainers/falkner.2bpp.lz" KarenPic: INCBIN "gfx/trainers/karen.2bpp.lz" NidorinaBackpic: INCBIN "gfx/pokemon/nidorina/back.2bpp.lz" TentacruelBackpic: INCBIN "gfx/pokemon/tentacruel/back.2bpp.lz" GrowlitheBackpic: INCBIN "gfx/pokemon/growlithe/back.2bpp.lz" KogaPic: INCBIN "gfx/trainers/koga.2bpp.lz" MachokeBackpic: INCBIN "gfx/pokemon/machoke/back.2bpp.lz" RaichuBackpic: INCBIN "gfx/pokemon/raichu/back.2bpp.lz" PoliwrathBackpic: INCBIN "gfx/pokemon/poliwrath/back.2bpp.lz" SwimmermPic: INCBIN "gfx/trainers/swimmer_m.2bpp.lz" SunkernFrontpic: INCBIN "gfx/pokemon/sunkern/front.animated.2bpp.lz" NidorinoBackpic: INCBIN "gfx/pokemon/nidorino/back.2bpp.lz" MysticalmanPic: INCBIN "gfx/trainers/mysticalman.2bpp.lz" CooltrainerfPic: INCBIN "gfx/trainers/cooltrainer_f.2bpp.lz" ElectrodeFrontpic: INCBIN "gfx/pokemon/electrode/front.animated.2bpp.lz" SECTION "Pics 14", ROMX SudowoodoBackpic: INCBIN "gfx/pokemon/sudowoodo/back.2bpp.lz" FlaaffyBackpic: INCBIN "gfx/pokemon/flaaffy/back.2bpp.lz" SentretFrontpic: INCBIN "gfx/pokemon/sentret/front.animated.2bpp.lz" TogeticBackpic: INCBIN "gfx/pokemon/togetic/back.2bpp.lz" BugsyPic: INCBIN "gfx/trainers/bugsy.2bpp.lz" MarowakBackpic: INCBIN "gfx/pokemon/marowak/back.2bpp.lz" GeodudeBackpic: INCBIN "gfx/pokemon/geodude/back.2bpp.lz" ScytherBackpic: INCBIN "gfx/pokemon/scyther/back.2bpp.lz" VileplumeBackpic: INCBIN "gfx/pokemon/vileplume/back.2bpp.lz" HitmonchanBackpic: INCBIN "gfx/pokemon/hitmonchan/back.2bpp.lz" JumpluffBackpic: INCBIN "gfx/pokemon/jumpluff/back.2bpp.lz" CooltrainermPic: INCBIN "gfx/trainers/cooltrainer_m.2bpp.lz" BlastoiseBackpic: INCBIN "gfx/pokemon/blastoise/back.2bpp.lz" MisdreavusBackpic: INCBIN "gfx/pokemon/misdreavus/back.2bpp.lz" TyrogueBackpic: INCBIN "gfx/pokemon/tyrogue/back.2bpp.lz" GeodudeFrontpic: INCBIN "gfx/pokemon/geodude/front.animated.2bpp.lz" ScizorBackpic: INCBIN "gfx/pokemon/scizor/back.2bpp.lz" GirafarigBackpic: INCBIN "gfx/pokemon/girafarig/back.2bpp.lz" StantlerBackpic: INCBIN "gfx/pokemon/stantler/back.2bpp.lz" SmeargleBackpic: INCBIN "gfx/pokemon/smeargle/back.2bpp.lz" CharizardBackpic: INCBIN "gfx/pokemon/charizard/back.2bpp.lz" KadabraBackpic: INCBIN "gfx/pokemon/kadabra/back.2bpp.lz" PrimeapeBackpic: INCBIN "gfx/pokemon/primeape/back.2bpp.lz" FurretBackpic: INCBIN "gfx/pokemon/furret/back.2bpp.lz" WartortleBackpic: INCBIN "gfx/pokemon/wartortle/back.2bpp.lz" ExeggcuteBackpic: INCBIN "gfx/pokemon/exeggcute/back.2bpp.lz" IgglybuffFrontpic: INCBIN "gfx/pokemon/igglybuff/front.animated.2bpp.lz" RaticateBackpic: INCBIN "gfx/pokemon/raticate/back.2bpp.lz" VulpixBackpic: INCBIN "gfx/pokemon/vulpix/back.2bpp.lz" EkansBackpic: INCBIN "gfx/pokemon/ekans/back.2bpp.lz" SeakingBackpic: INCBIN "gfx/pokemon/seaking/back.2bpp.lz" BurglarPic: INCBIN "gfx/trainers/burglar.2bpp.lz" PsyduckBackpic: INCBIN "gfx/pokemon/psyduck/back.2bpp.lz" PikachuBackpic: INCBIN "gfx/pokemon/pikachu/back.2bpp.lz" KabutoFrontpic: INCBIN "gfx/pokemon/kabuto/front.animated.2bpp.lz" MareepBackpic: INCBIN "gfx/pokemon/mareep/back.2bpp.lz" RemoraidBackpic: INCBIN "gfx/pokemon/remoraid/back.2bpp.lz" DittoFrontpic: INCBIN "gfx/pokemon/ditto/front.animated.2bpp.lz" KingdraBackpic: INCBIN "gfx/pokemon/kingdra/back.2bpp.lz" CamperPic: INCBIN "gfx/trainers/camper.2bpp.lz" WooperFrontpic: INCBIN "gfx/pokemon/wooper/front.animated.2bpp.lz" ClefairyBackpic: INCBIN "gfx/pokemon/clefairy/back.2bpp.lz" VenonatBackpic: INCBIN "gfx/pokemon/venonat/back.2bpp.lz" BellossomBackpic: INCBIN "gfx/pokemon/bellossom/back.2bpp.lz" Rival1Pic: INCBIN "gfx/trainers/rival1.2bpp.lz" SwinubBackpic: INCBIN "gfx/pokemon/swinub/back.2bpp.lz" SECTION "Pics 15", ROMX MewtwoBackpic: INCBIN "gfx/pokemon/mewtwo/back.2bpp.lz" PokemonProfPic: INCBIN "gfx/trainers/oak.2bpp.lz" CalPic: INCBIN "gfx/trainers/cal.2bpp.lz" SwimmerfPic: INCBIN "gfx/trainers/swimmer_f.2bpp.lz" DiglettFrontpic: INCBIN "gfx/pokemon/diglett/front.animated.2bpp.lz" OfficerPic: INCBIN "gfx/trainers/officer.2bpp.lz" MukBackpic: INCBIN "gfx/pokemon/muk/back.2bpp.lz" DelibirdBackpic: INCBIN "gfx/pokemon/delibird/back.2bpp.lz" SabrinaPic: INCBIN "gfx/trainers/sabrina.2bpp.lz" MagikarpBackpic: INCBIN "gfx/pokemon/magikarp/back.2bpp.lz" AriadosBackpic: INCBIN "gfx/pokemon/ariados/back.2bpp.lz" SneaselBackpic: INCBIN "gfx/pokemon/sneasel/back.2bpp.lz" UmbreonBackpic: INCBIN "gfx/pokemon/umbreon/back.2bpp.lz" MurkrowBackpic: INCBIN "gfx/pokemon/murkrow/back.2bpp.lz" IvysaurBackpic: INCBIN "gfx/pokemon/ivysaur/back.2bpp.lz" SlowbroBackpic: INCBIN "gfx/pokemon/slowbro/back.2bpp.lz" PsychicTPic: INCBIN "gfx/trainers/psychic_t.2bpp.lz" GolduckBackpic: INCBIN "gfx/pokemon/golduck/back.2bpp.lz" WeezingBackpic: INCBIN "gfx/pokemon/weezing/back.2bpp.lz" EnteiBackpic: INCBIN "gfx/pokemon/entei/back.2bpp.lz" GruntfPic: INCBIN "gfx/trainers/grunt_f.2bpp.lz" HorseaFrontpic: INCBIN "gfx/pokemon/horsea/front.animated.2bpp.lz" PidgeotBackpic: INCBIN "gfx/pokemon/pidgeot/back.2bpp.lz" HoOhBackpic: INCBIN "gfx/pokemon/ho_oh/back.2bpp.lz" PoliwhirlBackpic: INCBIN "gfx/pokemon/poliwhirl/back.2bpp.lz" MewBackpic: INCBIN "gfx/pokemon/mew/back.2bpp.lz" MachopBackpic: INCBIN "gfx/pokemon/machop/back.2bpp.lz" AbraBackpic: INCBIN "gfx/pokemon/abra/back.2bpp.lz" AerodactylBackpic: INCBIN "gfx/pokemon/aerodactyl/back.2bpp.lz" KakunaFrontpic: INCBIN "gfx/pokemon/kakuna/front.animated.2bpp.lz" DugtrioBackpic: INCBIN "gfx/pokemon/dugtrio/back.2bpp.lz" WeepinbellBackpic: INCBIN "gfx/pokemon/weepinbell/back.2bpp.lz" NidoranFBackpic: INCBIN "gfx/pokemon/nidoran_f/back.2bpp.lz" GravelerBackpic: INCBIN "gfx/pokemon/graveler/back.2bpp.lz" AipomBackpic: INCBIN "gfx/pokemon/aipom/back.2bpp.lz" EspeonBackpic: INCBIN "gfx/pokemon/espeon/back.2bpp.lz" WeedleFrontpic: INCBIN "gfx/pokemon/weedle/front.animated.2bpp.lz" TotodileBackpic: INCBIN "gfx/pokemon/totodile/back.2bpp.lz" SnubbullBackpic: INCBIN "gfx/pokemon/snubbull/back.2bpp.lz" KinglerBackpic: INCBIN "gfx/pokemon/kingler/back.2bpp.lz" GengarBackpic: INCBIN "gfx/pokemon/gengar/back.2bpp.lz" RattataBackpic: INCBIN "gfx/pokemon/rattata/back.2bpp.lz" YoungsterPic: INCBIN "gfx/trainers/youngster.2bpp.lz" WillPic: INCBIN "gfx/trainers/will.2bpp.lz" SchoolboyPic: INCBIN "gfx/trainers/schoolboy.2bpp.lz" MagnemiteFrontpic: INCBIN "gfx/pokemon/magnemite/front.animated.2bpp.lz" ErikaPic: INCBIN "gfx/trainers/erika.2bpp.lz" JaninePic: INCBIN "gfx/trainers/janine.2bpp.lz" MagnemiteBackpic: INCBIN "gfx/pokemon/magnemite/back.2bpp.lz" SECTION "Pics 16", ROMX HoothootBackpic: INCBIN "gfx/pokemon/hoothoot/back.2bpp.lz" NoctowlBackpic: INCBIN "gfx/pokemon/noctowl/back.2bpp.lz" MortyPic: INCBIN "gfx/trainers/morty.2bpp.lz" SlugmaBackpic: INCBIN "gfx/pokemon/slugma/back.2bpp.lz" KabutoBackpic: INCBIN "gfx/pokemon/kabuto/back.2bpp.lz" VictreebelBackpic: INCBIN "gfx/pokemon/victreebel/back.2bpp.lz" MeowthBackpic: INCBIN "gfx/pokemon/meowth/back.2bpp.lz" MeganiumBackpic: INCBIN "gfx/pokemon/meganium/back.2bpp.lz" PicnickerPic: INCBIN "gfx/trainers/picnicker.2bpp.lz" LickitungBackpic: INCBIN "gfx/pokemon/lickitung/back.2bpp.lz" TogepiFrontpic: INCBIN "gfx/pokemon/togepi/front.animated.2bpp.lz" SuperNerdPic: INCBIN "gfx/trainers/super_nerd.2bpp.lz" HaunterBackpic: INCBIN "gfx/pokemon/haunter/back.2bpp.lz" XatuBackpic: INCBIN "gfx/pokemon/xatu/back.2bpp.lz" RedPic: INCBIN "gfx/trainers/red.2bpp.lz" Porygon2Backpic: INCBIN "gfx/pokemon/porygon2/back.2bpp.lz" JasminePic: INCBIN "gfx/trainers/jasmine.2bpp.lz" PinecoBackpic: INCBIN "gfx/pokemon/pineco/back.2bpp.lz" MetapodFrontpic: INCBIN "gfx/pokemon/metapod/front.animated.2bpp.lz" SeelBackpic: INCBIN "gfx/pokemon/seel/back.2bpp.lz" QuagsireBackpic: INCBIN "gfx/pokemon/quagsire/back.2bpp.lz" WhitneyPic: INCBIN "gfx/trainers/whitney.2bpp.lz" JolteonBackpic: INCBIN "gfx/pokemon/jolteon/back.2bpp.lz" CaterpieFrontpic: INCBIN "gfx/pokemon/caterpie/front.animated.2bpp.lz" HoppipBackpic: INCBIN "gfx/pokemon/hoppip/back.2bpp.lz" BluePic: INCBIN "gfx/trainers/blue.2bpp.lz" GranbullBackpic: INCBIN "gfx/pokemon/granbull/back.2bpp.lz" GentlemanPic: INCBIN "gfx/trainers/gentleman.2bpp.lz" ExecutivemPic: INCBIN "gfx/trainers/executive_m.2bpp.lz" SpearowBackpic: INCBIN "gfx/pokemon/spearow/back.2bpp.lz" SunkernBackpic: INCBIN "gfx/pokemon/sunkern/back.2bpp.lz" LaprasBackpic: INCBIN "gfx/pokemon/lapras/back.2bpp.lz" MagbyBackpic: INCBIN "gfx/pokemon/magby/back.2bpp.lz" DragonairBackpic: INCBIN "gfx/pokemon/dragonair/back.2bpp.lz" ZapdosBackpic: INCBIN "gfx/pokemon/zapdos/back.2bpp.lz" ChikoritaBackpic: INCBIN "gfx/pokemon/chikorita/back.2bpp.lz" CorsolaBackpic: INCBIN "gfx/pokemon/corsola/back.2bpp.lz" ChinchouBackpic: INCBIN "gfx/pokemon/chinchou/back.2bpp.lz" ChanseyBackpic: INCBIN "gfx/pokemon/chansey/back.2bpp.lz" SkiploomBackpic: INCBIN "gfx/pokemon/skiploom/back.2bpp.lz" SpinarakFrontpic: INCBIN "gfx/pokemon/spinarak/front.animated.2bpp.lz" Rival2Pic: INCBIN "gfx/trainers/rival2.2bpp.lz" UnownWFrontpic: INCBIN "gfx/pokemon/unown_w/front.animated.2bpp.lz" CharmanderBackpic: INCBIN "gfx/pokemon/charmander/back.2bpp.lz" RhyhornBackpic: INCBIN "gfx/pokemon/rhyhorn/back.2bpp.lz" UnownCFrontpic: INCBIN "gfx/pokemon/unown_c/front.animated.2bpp.lz" MistyPic: INCBIN "gfx/trainers/misty.2bpp.lz" BlainePic: INCBIN "gfx/trainers/blaine.2bpp.lz" UnownZFrontpic: INCBIN "gfx/pokemon/unown_z/front.animated.2bpp.lz" SwinubFrontpic: INCBIN "gfx/pokemon/swinub/front.animated.2bpp.lz" LarvitarBackpic: INCBIN "gfx/pokemon/larvitar/back.2bpp.lz" PorygonBackpic: INCBIN "gfx/pokemon/porygon/back.2bpp.lz" UnownHBackpic: INCBIN "gfx/pokemon/unown_h/back.2bpp.lz" SECTION "Pics 17", ROMX ParasBackpic: INCBIN "gfx/pokemon/paras/back.2bpp.lz" VaporeonBackpic: INCBIN "gfx/pokemon/vaporeon/back.2bpp.lz" TentacoolBackpic: INCBIN "gfx/pokemon/tentacool/back.2bpp.lz" ExecutivefPic: INCBIN "gfx/trainers/executive_f.2bpp.lz" BulbasaurBackpic: INCBIN "gfx/pokemon/bulbasaur/back.2bpp.lz" SmoochumBackpic: INCBIN "gfx/pokemon/smoochum/back.2bpp.lz" PichuBackpic: INCBIN "gfx/pokemon/pichu/back.2bpp.lz" HoundoomBackpic: INCBIN "gfx/pokemon/houndoom/back.2bpp.lz" BellsproutBackpic: INCBIN "gfx/pokemon/bellsprout/back.2bpp.lz" GrimerBackpic: INCBIN "gfx/pokemon/grimer/back.2bpp.lz" LanturnBackpic: INCBIN "gfx/pokemon/lanturn/back.2bpp.lz" PidgeottoBackpic: INCBIN "gfx/pokemon/pidgeotto/back.2bpp.lz" StaryuBackpic: INCBIN "gfx/pokemon/staryu/back.2bpp.lz" MrMimeBackpic: INCBIN "gfx/pokemon/mr__mime/back.2bpp.lz" CaterpieBackpic: INCBIN "gfx/pokemon/caterpie/back.2bpp.lz" VoltorbFrontpic: INCBIN "gfx/pokemon/voltorb/front.animated.2bpp.lz" LugiaBackpic: INCBIN "gfx/pokemon/lugia/back.2bpp.lz" PrycePic: INCBIN "gfx/trainers/pryce.2bpp.lz" BrockPic: INCBIN "gfx/trainers/brock.2bpp.lz" UnownGFrontpic: INCBIN "gfx/pokemon/unown_g/front.animated.2bpp.lz" ArbokBackpic: INCBIN "gfx/pokemon/arbok/back.2bpp.lz" PolitoedBackpic: INCBIN "gfx/pokemon/politoed/back.2bpp.lz" DragoniteBackpic: INCBIN "gfx/pokemon/dragonite/back.2bpp.lz" HitmonleeBackpic: INCBIN "gfx/pokemon/hitmonlee/back.2bpp.lz" NatuFrontpic: INCBIN "gfx/pokemon/natu/front.animated.2bpp.lz" UrsaringBackpic: INCBIN "gfx/pokemon/ursaring/back.2bpp.lz" SagePic: INCBIN "gfx/trainers/sage.2bpp.lz" TeddiursaBackpic: INCBIN "gfx/pokemon/teddiursa/back.2bpp.lz" PhanpyBackpic: INCBIN "gfx/pokemon/phanpy/back.2bpp.lz" UnownVFrontpic: INCBIN "gfx/pokemon/unown_v/front.animated.2bpp.lz" KakunaBackpic: INCBIN "gfx/pokemon/kakuna/back.2bpp.lz" WobbuffetBackpic: INCBIN "gfx/pokemon/wobbuffet/back.2bpp.lz" TogepiBackpic: INCBIN "gfx/pokemon/togepi/back.2bpp.lz" CrobatBackpic: INCBIN "gfx/pokemon/crobat/back.2bpp.lz" BlisseyBackpic: INCBIN "gfx/pokemon/blissey/back.2bpp.lz" AmpharosBackpic: INCBIN "gfx/pokemon/ampharos/back.2bpp.lz" IgglybuffBackpic: INCBIN "gfx/pokemon/igglybuff/back.2bpp.lz" AzumarillBackpic: INCBIN "gfx/pokemon/azumarill/back.2bpp.lz" OctilleryBackpic: INCBIN "gfx/pokemon/octillery/back.2bpp.lz" UnownSFrontpic: INCBIN "gfx/pokemon/unown_s/front.animated.2bpp.lz" HorseaBackpic: INCBIN "gfx/pokemon/horsea/back.2bpp.lz" SentretBackpic: INCBIN "gfx/pokemon/sentret/back.2bpp.lz" UnownOFrontpic: INCBIN "gfx/pokemon/unown_o/front.animated.2bpp.lz" UnownTFrontpic: INCBIN "gfx/pokemon/unown_t/front.animated.2bpp.lz" WigglytuffBackpic: INCBIN "gfx/pokemon/wigglytuff/back.2bpp.lz" ArticunoBackpic: INCBIN "gfx/pokemon/articuno/back.2bpp.lz" DittoBackpic: INCBIN "gfx/pokemon/ditto/back.2bpp.lz" WeedleBackpic: INCBIN "gfx/pokemon/weedle/back.2bpp.lz" UnownHFrontpic: INCBIN "gfx/pokemon/unown_h/front.animated.2bpp.lz" CleffaBackpic: INCBIN "gfx/pokemon/cleffa/back.2bpp.lz" DrowzeeBackpic: INCBIN "gfx/pokemon/drowzee/back.2bpp.lz" GastlyBackpic: INCBIN "gfx/pokemon/gastly/back.2bpp.lz" FearowBackpic: INCBIN "gfx/pokemon/fearow/back.2bpp.lz" MarillBackpic: INCBIN "gfx/pokemon/marill/back.2bpp.lz" DratiniBackpic: INCBIN "gfx/pokemon/dratini/back.2bpp.lz" ElectrodeBackpic: INCBIN "gfx/pokemon/electrode/back.2bpp.lz" SkarmoryBackpic: INCBIN "gfx/pokemon/skarmory/back.2bpp.lz" MetapodBackpic: INCBIN "gfx/pokemon/metapod/back.2bpp.lz" JigglypuffBackpic: INCBIN "gfx/pokemon/jigglypuff/back.2bpp.lz" OddishBackpic: INCBIN "gfx/pokemon/oddish/back.2bpp.lz" UnownDBackpic: INCBIN "gfx/pokemon/unown_d/back.2bpp.lz" SECTION "Pics 18", ROMX SpinarakBackpic: INCBIN "gfx/pokemon/spinarak/back.2bpp.lz" RaikouBackpic: INCBIN "gfx/pokemon/raikou/back.2bpp.lz" UnownKFrontpic: INCBIN "gfx/pokemon/unown_k/front.animated.2bpp.lz" HoundourBackpic: INCBIN "gfx/pokemon/houndour/back.2bpp.lz" PoliwagBackpic: INCBIN "gfx/pokemon/poliwag/back.2bpp.lz" SquirtleBackpic: INCBIN "gfx/pokemon/squirtle/back.2bpp.lz" ShuckleBackpic: INCBIN "gfx/pokemon/shuckle/back.2bpp.lz" DewgongBackpic: INCBIN "gfx/pokemon/dewgong/back.2bpp.lz" UnownBFrontpic: INCBIN "gfx/pokemon/unown_b/front.animated.2bpp.lz" SlowpokeBackpic: INCBIN "gfx/pokemon/slowpoke/back.2bpp.lz" DunsparceBackpic: INCBIN "gfx/pokemon/dunsparce/back.2bpp.lz" DonphanBackpic: INCBIN "gfx/pokemon/donphan/back.2bpp.lz" WooperBackpic: INCBIN "gfx/pokemon/wooper/back.2bpp.lz" TaurosBackpic: INCBIN "gfx/pokemon/tauros/back.2bpp.lz" UnownXFrontpic: INCBIN "gfx/pokemon/unown_x/front.animated.2bpp.lz" UnownNFrontpic: INCBIN "gfx/pokemon/unown_n/front.animated.2bpp.lz" TangelaBackpic: INCBIN "gfx/pokemon/tangela/back.2bpp.lz" VoltorbBackpic: INCBIN "gfx/pokemon/voltorb/back.2bpp.lz" UnownJFrontpic: INCBIN "gfx/pokemon/unown_j/front.animated.2bpp.lz" MantineBackpic: INCBIN "gfx/pokemon/mantine/back.2bpp.lz" UnownLFrontpic: INCBIN "gfx/pokemon/unown_l/front.animated.2bpp.lz" PiloswineBackpic: INCBIN "gfx/pokemon/piloswine/back.2bpp.lz" UnownMFrontpic: INCBIN "gfx/pokemon/unown_m/front.animated.2bpp.lz" UnownFFrontpic: INCBIN "gfx/pokemon/unown_f/front.animated.2bpp.lz" NatuBackpic: INCBIN "gfx/pokemon/natu/back.2bpp.lz" UnownAFrontpic: INCBIN "gfx/pokemon/unown_a/front.animated.2bpp.lz" GolemBackpic: INCBIN "gfx/pokemon/golem/back.2bpp.lz" UnownUFrontpic: INCBIN "gfx/pokemon/unown_u/front.animated.2bpp.lz" DiglettBackpic: INCBIN "gfx/pokemon/diglett/back.2bpp.lz" UnownQFrontpic: INCBIN "gfx/pokemon/unown_q/front.animated.2bpp.lz" UnownPFrontpic: INCBIN "gfx/pokemon/unown_p/front.animated.2bpp.lz" UnownCBackpic: INCBIN "gfx/pokemon/unown_c/back.2bpp.lz" JynxBackpic: INCBIN "gfx/pokemon/jynx/back.2bpp.lz" GolbatBackpic: INCBIN "gfx/pokemon/golbat/back.2bpp.lz" UnownYFrontpic: INCBIN "gfx/pokemon/unown_y/front.animated.2bpp.lz" UnownGBackpic: INCBIN "gfx/pokemon/unown_g/back.2bpp.lz" UnownIFrontpic: INCBIN "gfx/pokemon/unown_i/front.animated.2bpp.lz" UnownVBackpic: INCBIN "gfx/pokemon/unown_v/back.2bpp.lz" ForretressBackpic: INCBIN "gfx/pokemon/forretress/back.2bpp.lz" UnownSBackpic: INCBIN "gfx/pokemon/unown_s/back.2bpp.lz" UnownRFrontpic: INCBIN "gfx/pokemon/unown_r/front.animated.2bpp.lz" UnownEBackpic: INCBIN "gfx/pokemon/unown_e/back.2bpp.lz" UnownJBackpic: INCBIN "gfx/pokemon/unown_j/back.2bpp.lz" UnownBBackpic: INCBIN "gfx/pokemon/unown_b/back.2bpp.lz" UnownOBackpic: INCBIN "gfx/pokemon/unown_o/back.2bpp.lz" UnownZBackpic: INCBIN "gfx/pokemon/unown_z/back.2bpp.lz" UnownWBackpic: INCBIN "gfx/pokemon/unown_w/back.2bpp.lz" UnownNBackpic: INCBIN "gfx/pokemon/unown_n/back.2bpp.lz" UnownABackpic: INCBIN "gfx/pokemon/unown_a/back.2bpp.lz" UnownMBackpic: INCBIN "gfx/pokemon/unown_m/back.2bpp.lz" UnownKBackpic: INCBIN "gfx/pokemon/unown_k/back.2bpp.lz" UnownTBackpic: INCBIN "gfx/pokemon/unown_t/back.2bpp.lz" UnownXBackpic: INCBIN "gfx/pokemon/unown_x/back.2bpp.lz" UnownLBackpic: INCBIN "gfx/pokemon/unown_l/back.2bpp.lz" UnownUBackpic: INCBIN "gfx/pokemon/unown_u/back.2bpp.lz" UnownQBackpic: INCBIN "gfx/pokemon/unown_q/back.2bpp.lz" UnownYBackpic: INCBIN "gfx/pokemon/unown_y/back.2bpp.lz" UnownPBackpic: INCBIN "gfx/pokemon/unown_p/back.2bpp.lz" UnownIBackpic: INCBIN "gfx/pokemon/unown_i/back.2bpp.lz" UnownRBackpic: INCBIN "gfx/pokemon/unown_r/back.2bpp.lz" FlambearFrontpic: INCBIN "gfx/pokemon/flambear/front.animated.2bpp.lz" FlambearBackpic: INCBIN "gfx/pokemon/flambear/back.2bpp.lz" SECTION "Pics 19", ROMX ; Seems to be an accidental copy of the previous bank SamuraiPic: INCBIN "gfx/trainers/samurai.2bpp.lz" AutistPic: INCBIN "gfx/trainers/chrischan.2bpp.lz"
[BITS 64] %include "parameters.inc" extern exit global and_int64 section .text and_int64: push rbp mov rax, ITERATIONS_and_int64 mov rbx, 1 mov rcx, 2 mov rdx, 3 mov rsi, 4 mov rdi, 5 mov r8, 6 mov r9, 7 mov r10, 8 mov r11, 9 mov r12, 10 mov r13, 11 mov r14, 12 mov r15, 13 .loop: and rbx, rbx and rcx, rcx and rdx, rdx and rsi, rsi and rdi, rdi and r8, r8 and r9, r9 and r10, r10 and r11, r11 and r12, r12 and r13, r13 and r14, r14 and r15, r15 dec rax jnz .loop .exit: lea rdi, [rel format] pop rbp xor rax, rax mov rax, ITERATIONS_and_int64 mov rsi, 15 ; 13 and + 1 dec + 1 loop mul rsi ret section .data format: db "%lu", 10, 0
; CALLER LINKAGE FOR FUNCTION POINTERS SECTION code_clib PUBLIC cplot PUBLIC _cplot EXTERN asm_cplot .cplot ._cplot pop af pop bc pop hl pop de push de push hl push bc push af jp asm_cplot
// // Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.16384 // // /// // Buffer Definitions: // // cbuffer cbPNTriangles // { // // float4x4 g_f4x4World; // Offset: 0 Size: 64 [unused] // float4x4 g_f4x4ViewProjection; // Offset: 64 Size: 64 [unused] // float4x4 g_f4x4WorldViewProjection;// Offset: 128 Size: 64 [unused] // float4 g_f4LightDir; // Offset: 192 Size: 16 [unused] // float4 g_f4Eye; // Offset: 208 Size: 16 [unused] // float4 g_f4ViewVector; // Offset: 224 Size: 16 [unused] // float4 g_f4TessFactors; // Offset: 240 Size: 16 // float4 g_f4ScreenParams; // Offset: 256 Size: 16 [unused] // float4 g_f4GUIParams1; // Offset: 272 Size: 16 [unused] // float4 g_f4GUIParams2; // Offset: 288 Size: 16 [unused] // float4 g_f4ViewFrustumPlanes[4]; // Offset: 304 Size: 64 [unused] // // } // // // Resource Bindings: // // Name Type Format Dim Slot Elements // ------------------------------ ---------- ------- ----------- ---- -------- // cbPNTriangles cbuffer NA NA 0 1 // // // // Patch Constant signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // SV_TessFactor 0 x 0 TRIEDGE float x // POSITION 3 yzw 0 NONE float yzw // SV_TessFactor 1 x 1 TRIEDGE float x // POSITION 4 yzw 1 NONE float yzw // SV_TessFactor 2 x 2 TRIEDGE float x // POSITION 5 yzw 2 NONE float yzw // SV_InsideTessFactor 0 x 3 TRIINT float x // POSITION 6 yzw 3 NONE float yzw // POSITION 7 xyz 4 NONE float xyz // POSITION 8 xyz 5 NONE float xyz // CENTER 0 xyz 6 NONE float xyz // NORMAL 3 xyz 7 NONE float xyz // NORMAL 4 xyz 8 NONE float xyz // NORMAL 5 xyz 9 NONE float xyz // // // Input signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // POSITION 0 xyz 0 NONE float xyz // NORMAL 0 xyz 1 NONE float xyz // TEXCOORD 0 xy 2 NONE float xy // // // Output signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // POSITION 0 xyz 0 NONE float xyz // NORMAL 0 xyz 1 NONE float xyz // TEXCOORD 0 xy 2 NONE float xy // // Tessellation Domain # of control points // -------------------- -------------------- // Triangle 3 // // Tessellation Output Primitive Partitioning Type // ------------------------------ ------------------ // Clockwise Triangles Odd Fractional // hs_5_0 hs_decls dcl_input_control_point_count 3 dcl_output_control_point_count 3 dcl_tessellator_domain domain_tri dcl_tessellator_partitioning partitioning_fractional_odd dcl_tessellator_output_primitive output_triangle_cw dcl_globalFlags refactoringAllowed dcl_constantbuffer cb0[16], immediateIndexed hs_fork_phase dcl_hs_fork_phase_instance_count 3 dcl_input vForkInstanceID dcl_output_siv o0.x, finalTriUeq0EdgeTessFactor dcl_output_siv o1.x, finalTriVeq0EdgeTessFactor dcl_output_siv o2.x, finalTriWeq0EdgeTessFactor dcl_temps 1 dcl_indexrange o0.x 3 mov r0.x, vForkInstanceID.x mov o[r0.x + 0].x, cb0[15].x ret hs_fork_phase dcl_output_siv o3.x, finalTriInsideTessFactor mul o3.x, cb0[15].x, l(1.000000) ret hs_fork_phase dcl_hs_fork_phase_instance_count 4 dcl_input vForkInstanceID dcl_input vicp[3][0].xyz dcl_input vicp[3][1].xyz dcl_output o0.yzw dcl_output o1.yzw dcl_output o2.yzw dcl_output o3.yzw dcl_temps 2 dcl_indexrange o0.yzw 4 iadd r0.xy, -vForkInstanceID.xxxx, l(1, 4, 0, 0) ult r0.z, vForkInstanceID.x, l(2) movc r0.x, r0.z, r0.x, r0.y iadd r0.y, vForkInstanceID.x, l(-1) movc r0.y, r0.z, vForkInstanceID.x, r0.y add r1.xyz, -vicp[r0.y + 0][0].xyzx, vicp[r0.x + 0][0].xyzx mad r0.xzw, vicp[r0.y + 0][0].xxyz, l(2.000000, 0.000000, 2.000000, 2.000000), vicp[r0.x + 0][0].xxyz dp3 r1.x, r1.xyzx, vicp[r0.y + 0][1].xyzx mad r0.xyz, -r1.xxxx, vicp[r0.y + 0][1].xyzx, r0.xzwx mul r0.xyz, r0.xyzx, l(0.333333, 0.333333, 0.333333, 0.000000) mov r0.w, vForkInstanceID.x mov o[r0.w + 0].yzw, r0.xxyz ret hs_fork_phase dcl_hs_fork_phase_instance_count 2 dcl_input vForkInstanceID dcl_input vicp[3][0].xyz dcl_input vicp[3][1].xyz dcl_output o4.xyz dcl_output o5.xyz dcl_temps 2 dcl_indexrange o4.xyz 2 ult r0.x, vForkInstanceID.x, l(1) movc r0.x, r0.x, l(0), l(2) iadd r0.y, vForkInstanceID.x, l(2) udiv null, r0.y, r0.y, l(3) add r1.xyz, -vicp[r0.y + 0][0].xyzx, vicp[r0.x + 0][0].xyzx mad r0.xzw, vicp[r0.y + 0][0].xxyz, l(2.000000, 0.000000, 2.000000, 2.000000), vicp[r0.x + 0][0].xxyz dp3 r1.x, r1.xyzx, vicp[r0.y + 0][1].xyzx mad r0.xyz, -r1.xxxx, vicp[r0.y + 0][1].xyzx, r0.xzwx mul r0.xyz, r0.xyzx, l(0.333333, 0.333333, 0.333333, 0.000000) mov r0.w, vForkInstanceID.x mov o[r0.w + 4].xyz, r0.xyzx ret hs_fork_phase dcl_hs_fork_phase_instance_count 3 dcl_input vForkInstanceID dcl_input vicp[3][0].xyz dcl_input vicp[3][1].xyz dcl_output o7.xyz dcl_output o8.xyz dcl_output o9.xyz dcl_temps 3 dcl_indexrange o7.xyz 3 iadd r0.x, vForkInstanceID.x, l(1) udiv null, r0.x, r0.x, l(3) mov r0.y, vForkInstanceID.x add r1.xyz, vicp[r0.x + 0][1].xyzx, vicp[r0.y + 0][1].xyzx add r0.xzw, -vicp[r0.y + 0][0].xxyz, vicp[r0.x + 0][0].xxyz dp3 r1.w, r0.xzwx, r1.xyzx add r1.w, r1.w, r1.w dp3 r2.x, r0.xzwx, r0.xzwx div r1.w, r1.w, r2.x mad r0.xzw, -r1.wwww, r0.xxzw, r1.xxyz dp3 r1.x, r0.xzwx, r0.xzwx rsq r1.x, r1.x mul r0.xzw, r0.xxzw, r1.xxxx mov o[r0.y + 7].xyz, r0.xzwx ret hs_join_phase dcl_input vpc0.y dcl_input vpc1.y dcl_input vpc2.y dcl_input vpc3.y dcl_input vpc4.x dcl_input vpc5.x dcl_input vicp[3][0].x dcl_output o6.x dcl_temps 1 add r0.x, vpc0.y, vpc1.y add r0.x, r0.x, vpc2.y add r0.x, r0.x, vpc3.y add r0.x, r0.x, vpc4.x add r0.x, r0.x, vpc5.x mul r0.x, r0.x, l(0.166667) add r0.y, vicp[1][0].x, vicp[0][0].x add r0.y, r0.y, vicp[2][0].x mad r0.y, -r0.y, l(0.333333), r0.x mad o6.x, r0.y, l(0.500000), r0.x ret hs_join_phase dcl_input vpc0.z dcl_input vpc1.z dcl_input vpc2.z dcl_input vpc3.z dcl_input vpc4.y dcl_input vpc5.y dcl_input vicp[3][0].y dcl_output o6.y dcl_temps 1 add r0.x, vpc0.z, vpc1.z add r0.x, r0.x, vpc2.z add r0.x, r0.x, vpc3.z add r0.x, r0.x, vpc4.y add r0.x, r0.x, vpc5.y mul r0.x, r0.x, l(0.166667) add r0.y, vicp[1][0].y, vicp[0][0].y add r0.y, r0.y, vicp[2][0].y mad r0.y, -r0.y, l(0.333333), r0.x mad o6.y, r0.y, l(0.500000), r0.x ret hs_join_phase dcl_input vpc0.w dcl_input vpc1.w dcl_input vpc2.w dcl_input vpc3.w dcl_input vpc4.z dcl_input vpc5.z dcl_input vicp[3][0].z dcl_output o6.z dcl_temps 1 add r0.x, vpc0.w, vpc1.w add r0.x, r0.x, vpc2.w add r0.x, r0.x, vpc3.w add r0.x, r0.x, vpc4.z add r0.x, r0.x, vpc5.z mul r0.x, r0.x, l(0.166667) add r0.y, vicp[1][0].z, vicp[0][0].z add r0.y, r0.y, vicp[2][0].z mad r0.y, -r0.y, l(0.333333), r0.x mad o6.z, r0.y, l(0.500000), r0.x ret // Approximately 78 instruction slots used
; A001748: 3 * primes. ; 6,9,15,21,33,39,51,57,69,87,93,111,123,129,141,159,177,183,201,213,219,237,249,267,291,303,309,321,327,339,381,393,411,417,447,453,471,489,501,519,537,543,573,579,591,597,633,669,681,687,699,717,723,753,771,789,807,813,831,843,849,879,921,933,939,951,993,1011,1041,1047,1059,1077,1101,1119,1137,1149,1167,1191,1203,1227,1257,1263,1293,1299,1317,1329,1347,1371,1383,1389,1401,1437,1461,1473,1497,1509,1527,1563,1569,1623,1641,1671,1689,1707,1713,1731,1761,1779,1797,1803,1821,1839,1851,1857,1893,1923,1929,1941,1959,1977,1983,2019,2031,2049,2073,2103,2127,2157,2181,2199,2217,2229,2253,2271,2283,2307,2319,2361,2391,2427,2433,2463,2469,2481,2487,2517,2559,2571,2577,2589,2631,2643,2649,2661,2721,2733,2757,2787,2811,2823,2841,2859,2901,2913,2931,2949,2973,2991,3027,3039,3057,3063,3093,3099,3117,3147,3153,3183,3189,3207,3261,3273,3279,3291,3309,3327,3351,3369,3387,3453,3459,3489,3513,3543,3561,3579,3603,3639,3651,3669,3687,3693,3711,3747,3777,3831,3837,3849,3867,3873,3891,3903,3909,3921,3957,3963,3981,4083,4101,4119,4143,4197,4227,4269,4281,4287,4299,4317,4341,4353,4359,4377,4413,4443,4449,4461,4467,4479,4497,4533,4569,4593,4629,4647,4659,4677,4701,4713,4737,4749 cal $0,40 ; The prime numbers. mov $1,$0 sub $1,2 mul $1,3 add $1,6
; A158135: a(n) = 144*n^2 - 2*n. ; 142,572,1290,2296,3590,5172,7042,9200,11646,14380,17402,20712,24310,28196,32370,36832,41582,46620,51946,57560,63462,69652,76130,82896,89950,97292,104922,112840,121046,129540,138322,147392,156750,166396,176330,186552,197062,207860,218946,230320,241982,253932,266170,278696,291510,304612,318002,331680,345646,359900,374442,389272,404390,419796,435490,451472,467742,484300,501146,518280,535702,553412,571410,589696,608270,627132,646282,665720,685446,705460,725762,746352,767230,788396,809850,831592 add $0,1 mul $0,72 bin $0,2 div $0,36 mul $0,2
/* Develop by Luis Alberto email: alberto.bsd@gmail.com gcc -o bPfile bPfile.c -lgmp -lm Hint: compile in the keyhunt directory */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <gmp.h> #include <string.h> #ifdef WIN64 #include <Windows.h> #else #include <unistd.h> #include <pthread.h> #endif #include <math.h> #include "util.h" #define BSGS_BUFFERXPOINTLENGTH 32 #define BSGS_BUFFERREGISTERLENGTH 36 struct Point { mpz_t x; mpz_t y; }; struct Elliptic_Curve { mpz_t p; mpz_t n; }; const char* EC_constant_N = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"; const char* EC_constant_P = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"; const char* EC_constant_Gx = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; const char* EC_constant_Gy = "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"; struct Point DoublingG[256]; void Point_Doubling(struct Point* P, struct Point* R); void Point_Addition(struct Point* P, struct Point* Q, struct Point* R); void Scalar_Multiplication(struct Point P, struct Point* R, mpz_t m); void Point_Negation(struct Point* A, struct Point* S); void init_doublingG(struct Point* P); struct Elliptic_Curve EC; struct Point G; int main(int argc, char** argv) { mpz_t temp; FILE* p_file; char temporal[512], rawvalue[BSGS_BUFFERXPOINTLENGTH]; long int i, m, sz; mpz_t M; struct Point point_t, P; if (argc < 3) { printf("Create bP File usage\n"); printf("%s <bP items> <output filename>\n\n", argv[0]); printf("Example to create a File with 1 Billion items:\n%s 1000000000 Pfile.bin\n", argv[0]); printf("If the file exists, only the missing bP items will be added○\n"); exit(0); } mpz_init_set_str(M, argv[1], 10); mpz_init_set_str(EC.p, EC_constant_P, 16); mpz_init_set_str(EC.n, EC_constant_N, 16); mpz_init_set_str(G.x, EC_constant_Gx, 16); mpz_init_set_str(G.y, EC_constant_Gy, 16); init_doublingG(&G); mpz_init(point_t.x); mpz_init(point_t.y); mpz_init(temp); m = mpz_get_ui(M); mpz_init_set(P.x, G.x); mpz_init_set(P.y, G.y); p_file = fopen(argv[2], "wb"); if (p_file == NULL) { printf("Can't create file %s\n", argv[2]); exit(0); } /* fseek(p_file, 0L, SEEK_END); sz = ftell(p_file); if(sz % 32 != 0) { printf("Invalid filesize\n"); exit(0); } printf("Current numeber of items %li\n",(long int)(sz/32)); if(m <= sz/32 ) { printf("The current file have %li items\n",m); } else { i = m-(sz/32); printf("OK, items missing %li\n",i); } mpz_set_ui(temp,i) */ i = 0; printf("[+] precalculating %li bP elements in file %s\n", m, argv[2]); do { mpz_set(point_t.x, P.x); mpz_set(point_t.y, P.y); gmp_sprintf(temporal, "%0.64Zx", P.x); hexs2bin(temporal, (unsigned char*)rawvalue); fwrite(rawvalue, 1, 32, p_file); Point_Addition(&G, &point_t, &P); i++; } while (i < m); } void Point_Doubling(struct Point* P, struct Point* R) { mpz_t slope, temp; mpz_init(temp); mpz_init(slope); if (mpz_cmp_ui(P->y, 0) != 0) { mpz_mul_ui(temp, P->y, 2); mpz_invert(temp, temp, EC.p); mpz_mul(slope, P->x, P->x); mpz_mul_ui(slope, slope, 3); mpz_mul(slope, slope, temp); mpz_mod(slope, slope, EC.p); mpz_mul(R->x, slope, slope); mpz_sub(R->x, R->x, P->x); mpz_sub(R->x, R->x, P->x); mpz_mod(R->x, R->x, EC.p); mpz_sub(temp, P->x, R->x); mpz_mul(R->y, slope, temp); mpz_sub(R->y, R->y, P->y); mpz_mod(R->y, R->y, EC.p); } else { mpz_set_ui(R->x, 0); mpz_set_ui(R->y, 0); } mpz_clear(temp); mpz_clear(slope); } void Point_Addition(struct Point* P, struct Point* Q, struct Point* R) { mpz_t PA_temp, PA_slope; mpz_init(PA_temp); mpz_init(PA_slope); mpz_mod(Q->x, Q->x, EC.p); mpz_mod(Q->y, Q->y, EC.p); mpz_mod(P->x, P->x, EC.p); mpz_mod(P->y, P->y, EC.p); if (mpz_cmp_ui(P->x, 0) == 0 && mpz_cmp_ui(P->y, 0) == 0) { mpz_set(R->x, Q->x); mpz_set(R->y, Q->y); } else { /* This is commented because Q never 0,0, always is kG point*/ /* if(mpz_cmp_ui(Q->x, 0) == 0 && mpz_cmp_ui(Q->y, 0) == 0) { mpz_set(R->x, P->x); mpz_set(R->y, P->y); } else { */ if (mpz_cmp_ui(Q->y, 0) != 0) { mpz_sub(PA_temp, EC.p, Q->y); mpz_mod(PA_temp, PA_temp, EC.p); } else { mpz_set_ui(PA_temp, 0); } if (mpz_cmp(P->y, PA_temp) == 0 && mpz_cmp(P->x, Q->x) == 0) { mpz_set_ui(R->x, 0); mpz_set_ui(R->y, 0); } else { if (mpz_cmp(P->x, Q->x) == 0 && mpz_cmp(P->y, Q->y) == 0) { Point_Doubling(P, R); } else { mpz_set_ui(PA_slope, 0); mpz_sub(PA_temp, P->x, Q->x); mpz_mod(PA_temp, PA_temp, EC.p); mpz_invert(PA_temp, PA_temp, EC.p); mpz_sub(PA_slope, P->y, Q->y); mpz_mul(PA_slope, PA_slope, PA_temp); mpz_mod(PA_slope, PA_slope, EC.p); mpz_mul(R->x, PA_slope, PA_slope); mpz_sub(R->x, R->x, P->x); mpz_sub(R->x, R->x, Q->x); mpz_mod(R->x, R->x, EC.p); mpz_sub(PA_temp, P->x, R->x); mpz_mul(R->y, PA_slope, PA_temp); mpz_sub(R->y, R->y, P->y); mpz_mod(R->y, R->y, EC.p); } } //} } mpz_clear(PA_temp); mpz_clear(PA_slope); } void Scalar_Multiplication(struct Point P, struct Point* R, mpz_t m) { char strtemp[65]; struct Point SM_T, SM_Q; long no_of_bits, i; no_of_bits = mpz_sizeinbase(m, 2); mpz_init_set_ui(SM_Q.x, 0); mpz_init_set_ui(SM_Q.y, 0); mpz_init_set_ui(SM_T.x, 0); mpz_init_set_ui(SM_T.y, 0); mpz_set_ui(R->x, 0); mpz_set_ui(R->y, 0); if (mpz_cmp_ui(m, 0) != 0) { mpz_set(SM_Q.x, P.x); mpz_set(SM_Q.y, P.y); for (i = 0; i < no_of_bits; i++) { if (mpz_tstbit(m, i)) { mpz_set(SM_T.x, R->x); mpz_set(SM_T.y, R->y); mpz_set(SM_Q.x, DoublingG[i].x); mpz_set(SM_Q.y, DoublingG[i].y); Point_Addition(&SM_T, &SM_Q, R); } } } mpz_clear(SM_T.x); mpz_clear(SM_T.y); mpz_clear(SM_Q.x); mpz_clear(SM_Q.y); } void Point_Negation(struct Point* A, struct Point* S) { mpz_sub(S->y, EC.p, A->y); mpz_set(S->x, A->x); } void init_doublingG(struct Point* P) { int i = 0; mpz_init(DoublingG[i].x); mpz_init(DoublingG[i].y); mpz_set(DoublingG[i].x, P->x); mpz_set(DoublingG[i].y, P->y); i = 1; while (i < 256) { mpz_init(DoublingG[i].x); mpz_init(DoublingG[i].y); Point_Doubling(&DoublingG[i - 1], &DoublingG[i]); mpz_mod(DoublingG[i].x, DoublingG[i].x, EC.p); mpz_mod(DoublingG[i].y, DoublingG[i].y, EC.p); i++; } }
; A204042: The number of functions f:{1,2,...,n}->{1,2,...,n} (endofunctions) such that all of the fixed points in f are isolated. ; Submitted by Jon Maiga ; 1,1,2,12,120,1520,23160,413952,8505280,197631072,5125527360,146787894440,4601174623584,156693888150384,5761055539858528,227438694372072120,9596077520725211520,430920897407809702208,20520683482765477749120,1032920864149903149579336,54797532208320308334631840,3055883810524796131963597200,178716799508583497217246982176,10937310247806884068071321106136,699064487173517195055849335632704,46580207337775746406510678244997600,3230289720887508868334824903300091200,232793662300334135737038581433242902632 mov $4,$0 add $0,1 lpb $0 sub $0,1 mov $2,$0 pow $2,$1 mov $3,$4 bin $3,$1 mov $1,$0 mul $3,$2 add $5,$3 lpe mov $0,$5
//===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file contains the implementation of the UnwrappedLineParser, /// which turns a stream of tokens into UnwrappedLines. /// //===----------------------------------------------------------------------===// #include "UnwrappedLineParser.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #define DEBUG_TYPE "format-parser" namespace clang { namespace format { class FormatTokenSource { public: virtual ~FormatTokenSource() {} virtual FormatToken *getNextToken() = 0; virtual unsigned getPosition() = 0; virtual FormatToken *setPosition(unsigned Position) = 0; }; namespace { class ScopedDeclarationState { public: ScopedDeclarationState(UnwrappedLine &Line, std::vector<bool> &Stack, bool MustBeDeclaration) : Line(Line), Stack(Stack) { Line.MustBeDeclaration = MustBeDeclaration; Stack.push_back(MustBeDeclaration); } ~ScopedDeclarationState() { Stack.pop_back(); if (!Stack.empty()) Line.MustBeDeclaration = Stack.back(); else Line.MustBeDeclaration = true; } private: UnwrappedLine &Line; std::vector<bool> &Stack; }; class ScopedMacroState : public FormatTokenSource { public: ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource, FormatToken *&ResetToken) : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken), PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource), Token(nullptr) { TokenSource = this; Line.Level = 0; Line.InPPDirective = true; } ~ScopedMacroState() override { TokenSource = PreviousTokenSource; ResetToken = Token; Line.InPPDirective = false; Line.Level = PreviousLineLevel; } FormatToken *getNextToken() override { // The \c UnwrappedLineParser guards against this by never calling // \c getNextToken() after it has encountered the first eof token. assert(!eof()); Token = PreviousTokenSource->getNextToken(); if (eof()) return getFakeEOF(); return Token; } unsigned getPosition() override { return PreviousTokenSource->getPosition(); } FormatToken *setPosition(unsigned Position) override { Token = PreviousTokenSource->setPosition(Position); return Token; } private: bool eof() { return Token && Token->HasUnescapedNewline; } FormatToken *getFakeEOF() { static bool EOFInitialized = false; static FormatToken FormatTok; if (!EOFInitialized) { FormatTok.Tok.startToken(); FormatTok.Tok.setKind(tok::eof); EOFInitialized = true; } return &FormatTok; } UnwrappedLine &Line; FormatTokenSource *&TokenSource; FormatToken *&ResetToken; unsigned PreviousLineLevel; FormatTokenSource *PreviousTokenSource; FormatToken *Token; }; } // end anonymous namespace class ScopedLineState { public: ScopedLineState(UnwrappedLineParser &Parser, bool SwitchToPreprocessorLines = false) : Parser(Parser), OriginalLines(Parser.CurrentLines) { if (SwitchToPreprocessorLines) Parser.CurrentLines = &Parser.PreprocessorDirectives; else if (!Parser.Line->Tokens.empty()) Parser.CurrentLines = &Parser.Line->Tokens.back().Children; PreBlockLine = std::move(Parser.Line); Parser.Line = llvm::make_unique<UnwrappedLine>(); Parser.Line->Level = PreBlockLine->Level; Parser.Line->InPPDirective = PreBlockLine->InPPDirective; } ~ScopedLineState() { if (!Parser.Line->Tokens.empty()) { Parser.addUnwrappedLine(); } assert(Parser.Line->Tokens.empty()); Parser.Line = std::move(PreBlockLine); if (Parser.CurrentLines == &Parser.PreprocessorDirectives) Parser.MustBreakBeforeNextToken = true; Parser.CurrentLines = OriginalLines; } private: UnwrappedLineParser &Parser; std::unique_ptr<UnwrappedLine> PreBlockLine; SmallVectorImpl<UnwrappedLine> *OriginalLines; }; class CompoundStatementIndenter { public: CompoundStatementIndenter(UnwrappedLineParser *Parser, const FormatStyle &Style, unsigned &LineLevel) : LineLevel(LineLevel), OldLineLevel(LineLevel) { if (Style.BreakBeforeBraces == FormatStyle::BS_Allman) { Parser->addUnwrappedLine(); } else if (Style.BreakBeforeBraces == FormatStyle::BS_GNU) { Parser->addUnwrappedLine(); ++LineLevel; } } ~CompoundStatementIndenter() { LineLevel = OldLineLevel; } private: unsigned &LineLevel; unsigned OldLineLevel; }; namespace { class IndexedTokenSource : public FormatTokenSource { public: IndexedTokenSource(ArrayRef<FormatToken *> Tokens) : Tokens(Tokens), Position(-1) {} FormatToken *getNextToken() override { ++Position; return Tokens[Position]; } unsigned getPosition() override { assert(Position >= 0); return Position; } FormatToken *setPosition(unsigned P) override { Position = P; return Tokens[Position]; } void reset() { Position = -1; } private: ArrayRef<FormatToken *> Tokens; int Position; }; } // end anonymous namespace UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style, const AdditionalKeywords &Keywords, ArrayRef<FormatToken *> Tokens, UnwrappedLineConsumer &Callback) : Line(new UnwrappedLine), MustBreakBeforeNextToken(false), CurrentLines(&Lines), Style(Style), Keywords(Keywords), Tokens(nullptr), Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1) {} void UnwrappedLineParser::reset() { PPBranchLevel = -1; Line.reset(new UnwrappedLine); CommentsBeforeNextToken.clear(); FormatTok = nullptr; MustBreakBeforeNextToken = false; PreprocessorDirectives.clear(); CurrentLines = &Lines; DeclarationScopeStack.clear(); PPStack.clear(); } void UnwrappedLineParser::parse() { IndexedTokenSource TokenSource(AllTokens); do { DEBUG(llvm::dbgs() << "----\n"); reset(); Tokens = &TokenSource; TokenSource.reset(); readToken(); parseFile(); // Create line with eof token. pushToken(FormatTok); addUnwrappedLine(); for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(), E = Lines.end(); I != E; ++I) { Callback.consumeUnwrappedLine(*I); } Callback.finishRun(); Lines.clear(); while (!PPLevelBranchIndex.empty() && PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) { PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1); PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1); } if (!PPLevelBranchIndex.empty()) { ++PPLevelBranchIndex.back(); assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size()); assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back()); } } while (!PPLevelBranchIndex.empty()); } void UnwrappedLineParser::parseFile() { // The top-level context in a file always has declarations, except for pre- // processor directives and JavaScript files. bool MustBeDeclaration = !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript; ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, MustBeDeclaration); parseLevel(/*HasOpeningBrace=*/false); // Make sure to format the remaining tokens. flushComments(true); addUnwrappedLine(); } void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) { bool SwitchLabelEncountered = false; do { tok::TokenKind kind = FormatTok->Tok.getKind(); if (FormatTok->Type == TT_MacroBlockBegin) { kind = tok::l_brace; } else if (FormatTok->Type == TT_MacroBlockEnd) { kind = tok::r_brace; } switch (kind) { case tok::comment: nextToken(); addUnwrappedLine(); break; case tok::l_brace: // FIXME: Add parameter whether this can happen - if this happens, we must // be in a non-declaration context. if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList()) continue; parseBlock(/*MustBeDeclaration=*/false); addUnwrappedLine(); break; case tok::r_brace: if (HasOpeningBrace) return; nextToken(); addUnwrappedLine(); break; case tok::kw_default: case tok::kw_case: if (!SwitchLabelEncountered && (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1))) ++Line->Level; SwitchLabelEncountered = true; parseStructuralElement(); break; default: parseStructuralElement(); break; } } while (!eof()); } void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { // We'll parse forward through the tokens until we hit // a closing brace or eof - note that getNextToken() will // parse macros, so this will magically work inside macro // definitions, too. unsigned StoredPosition = Tokens->getPosition(); FormatToken *Tok = FormatTok; // Keep a stack of positions of lbrace tokens. We will // update information about whether an lbrace starts a // braced init list or a different block during the loop. SmallVector<FormatToken *, 8> LBraceStack; assert(Tok->Tok.is(tok::l_brace)); do { // Get next none-comment token. FormatToken *NextTok; unsigned ReadTokens = 0; do { NextTok = Tokens->getNextToken(); ++ReadTokens; } while (NextTok->is(tok::comment)); switch (Tok->Tok.getKind()) { case tok::l_brace: Tok->BlockKind = BK_Unknown; LBraceStack.push_back(Tok); break; case tok::r_brace: if (!LBraceStack.empty()) { if (LBraceStack.back()->BlockKind == BK_Unknown) { bool ProbablyBracedList = false; if (Style.Language == FormatStyle::LK_Proto) { ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square); } else { // Using OriginalColumn to distinguish between ObjC methods and // binary operators is a bit hacky. bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) && NextTok->OriginalColumn == 0; // If there is a comma, semicolon or right paren after the closing // brace, we assume this is a braced initializer list. Note that // regardless how we mark inner braces here, we will overwrite the // BlockKind later if we parse a braced list (where all blocks // inside are by default braced lists), or when we explicitly detect // blocks (for example while parsing lambdas). // // We exclude + and - as they can be ObjC visibility modifiers. ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::period, tok::colon, tok::r_paren, tok::r_square, tok::l_brace, tok::l_paren, tok::ellipsis) || (NextTok->is(tok::semi) && (!ExpectClassBody || LBraceStack.size() != 1)) || (NextTok->isBinaryOperator() && !NextIsObjCMethod); } if (ProbablyBracedList) { Tok->BlockKind = BK_BracedInit; LBraceStack.back()->BlockKind = BK_BracedInit; } else { Tok->BlockKind = BK_Block; LBraceStack.back()->BlockKind = BK_Block; } } LBraceStack.pop_back(); } break; case tok::at: case tok::semi: case tok::kw_if: case tok::kw_while: case tok::kw_for: case tok::kw_switch: case tok::kw_try: case tok::kw___try: if (!LBraceStack.empty()) LBraceStack.back()->BlockKind = BK_Block; break; default: break; } Tok = NextTok; } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty()); // Assume other blocks for all unclosed opening braces. for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) { if (LBraceStack[i]->BlockKind == BK_Unknown) LBraceStack[i]->BlockKind = BK_Block; } FormatTok = Tokens->setPosition(StoredPosition); } void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel, bool MunchSemi) { assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) && "'{' or macro block token expected"); const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin); unsigned InitialLevel = Line->Level; nextToken(); if (MacroBlock && FormatTok->is(tok::l_paren)) parseParens(); addUnwrappedLine(); ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, MustBeDeclaration); if (AddLevel) ++Line->Level; parseLevel(/*HasOpeningBrace=*/true); if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd) : !FormatTok->is(tok::r_brace)) { Line->Level = InitialLevel; return; } nextToken(); // Munch the closing brace. if (MacroBlock && FormatTok->is(tok::l_paren)) parseParens(); if (MunchSemi && FormatTok->Tok.is(tok::semi)) nextToken(); Line->Level = InitialLevel; } static bool isGoogScope(const UnwrappedLine &Line) { // FIXME: Closure-library specific stuff should not be hard-coded but be // configurable. if (Line.Tokens.size() < 4) return false; auto I = Line.Tokens.begin(); if (I->Tok->TokenText != "goog") return false; ++I; if (I->Tok->isNot(tok::period)) return false; ++I; if (I->Tok->TokenText != "scope") return false; ++I; return I->Tok->is(tok::l_paren); } static bool ShouldBreakBeforeBrace(const FormatStyle &Style, const FormatToken &InitialToken) { switch (Style.BreakBeforeBraces) { case FormatStyle::BS_Linux: return InitialToken.isOneOf(tok::kw_namespace, tok::kw_class); case FormatStyle::BS_Mozilla: return InitialToken.isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union); case FormatStyle::BS_Allman: case FormatStyle::BS_GNU: return true; default: return false; } } void UnwrappedLineParser::parseChildBlock() { FormatTok->BlockKind = BK_Block; nextToken(); { bool GoogScope = Style.Language == FormatStyle::LK_JavaScript && isGoogScope(*Line); ScopedLineState LineState(*this); ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, /*MustBeDeclaration=*/false); Line->Level += GoogScope ? 0 : 1; parseLevel(/*HasOpeningBrace=*/true); flushComments(isOnNewLine(*FormatTok)); Line->Level -= GoogScope ? 0 : 1; } nextToken(); } void UnwrappedLineParser::parsePPDirective() { assert(FormatTok->Tok.is(tok::hash) && "'#' expected"); ScopedMacroState MacroState(*Line, Tokens, FormatTok); nextToken(); if (!FormatTok->Tok.getIdentifierInfo()) { parsePPUnknown(); return; } switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) { case tok::pp_define: parsePPDefine(); return; case tok::pp_if: parsePPIf(/*IfDef=*/false); break; case tok::pp_ifdef: case tok::pp_ifndef: parsePPIf(/*IfDef=*/true); break; case tok::pp_else: parsePPElse(); break; case tok::pp_elif: parsePPElIf(); break; case tok::pp_endif: parsePPEndIf(); break; default: parsePPUnknown(); break; } } void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) { if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable)) PPStack.push_back(PP_Unreachable); else PPStack.push_back(PP_Conditional); } void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) { ++PPBranchLevel; assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size()); if (PPBranchLevel == (int)PPLevelBranchIndex.size()) { PPLevelBranchIndex.push_back(0); PPLevelBranchCount.push_back(0); } PPChainBranchIndex.push(0); bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0; conditionalCompilationCondition(Unreachable || Skip); } void UnwrappedLineParser::conditionalCompilationAlternative() { if (!PPStack.empty()) PPStack.pop_back(); assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); if (!PPChainBranchIndex.empty()) ++PPChainBranchIndex.top(); conditionalCompilationCondition( PPBranchLevel >= 0 && !PPChainBranchIndex.empty() && PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top()); } void UnwrappedLineParser::conditionalCompilationEnd() { assert(PPBranchLevel < (int)PPLevelBranchIndex.size()); if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) { if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) { PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1; } } // Guard against #endif's without #if. if (PPBranchLevel > 0) --PPBranchLevel; if (!PPChainBranchIndex.empty()) PPChainBranchIndex.pop(); if (!PPStack.empty()) PPStack.pop_back(); } void UnwrappedLineParser::parsePPIf(bool IfDef) { nextToken(); bool IsLiteralFalse = (FormatTok->Tok.isLiteral() && FormatTok->Tok.getLiteralData() != nullptr && StringRef(FormatTok->Tok.getLiteralData(), FormatTok->Tok.getLength()) == "0") || FormatTok->Tok.is(tok::kw_false); conditionalCompilationStart(!IfDef && IsLiteralFalse); parsePPUnknown(); } void UnwrappedLineParser::parsePPElse() { conditionalCompilationAlternative(); parsePPUnknown(); } void UnwrappedLineParser::parsePPElIf() { parsePPElse(); } void UnwrappedLineParser::parsePPEndIf() { conditionalCompilationEnd(); parsePPUnknown(); } void UnwrappedLineParser::parsePPDefine() { nextToken(); if (FormatTok->Tok.getKind() != tok::identifier) { parsePPUnknown(); return; } nextToken(); if (FormatTok->Tok.getKind() == tok::l_paren && FormatTok->WhitespaceRange.getBegin() == FormatTok->WhitespaceRange.getEnd()) { parseParens(); } addUnwrappedLine(); Line->Level = 1; // Errors during a preprocessor directive can only affect the layout of the // preprocessor directive, and thus we ignore them. An alternative approach // would be to use the same approach we use on the file level (no // re-indentation if there was a structural error) within the macro // definition. parseFile(); } void UnwrappedLineParser::parsePPUnknown() { do { nextToken(); } while (!eof()); addUnwrappedLine(); } // Here we blacklist certain tokens that are not usually the first token in an // unwrapped line. This is used in attempt to distinguish macro calls without // trailing semicolons from other constructs split to several lines. static bool tokenCanStartNewLine(const clang::Token &Tok) { // Semicolon can be a null-statement, l_square can be a start of a macro or // a C++11 attribute, but this doesn't seem to be common. return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) && Tok.isNot(tok::l_square) && // Tokens that can only be used as binary operators and a part of // overloaded operator names. Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) && Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) && Tok.isNot(tok::less) && Tok.isNot(tok::greater) && Tok.isNot(tok::slash) && Tok.isNot(tok::percent) && Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) && Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) && Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) && Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) && Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) && Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) && Tok.isNot(tok::lesslessequal) && // Colon is used in labels, base class lists, initializer lists, // range-based for loops, ternary operator, but should never be the // first token in an unwrapped line. Tok.isNot(tok::colon) && // 'noexcept' is a trailing annotation. Tok.isNot(tok::kw_noexcept); } void UnwrappedLineParser::parseStructuralElement() { assert(!FormatTok->Tok.is(tok::l_brace)); switch (FormatTok->Tok.getKind()) { case tok::at: nextToken(); if (FormatTok->Tok.is(tok::l_brace)) { parseBracedList(); break; } switch (FormatTok->Tok.getObjCKeywordID()) { case tok::objc_public: case tok::objc_protected: case tok::objc_package: case tok::objc_private: return parseAccessSpecifier(); case tok::objc_interface: case tok::objc_implementation: return parseObjCInterfaceOrImplementation(); case tok::objc_protocol: return parseObjCProtocol(); case tok::objc_end: return; // Handled by the caller. case tok::objc_optional: case tok::objc_required: nextToken(); addUnwrappedLine(); return; case tok::objc_autoreleasepool: nextToken(); if (FormatTok->Tok.is(tok::l_brace)) { if (Style.BreakBeforeBraces == FormatStyle::BS_Allman || Style.BreakBeforeBraces == FormatStyle::BS_GNU) addUnwrappedLine(); parseBlock(/*MustBeDeclaration=*/false); } addUnwrappedLine(); return; case tok::objc_try: // This branch isn't strictly necessary (the kw_try case below would // do this too after the tok::at is parsed above). But be explicit. parseTryCatch(); return; default: break; } break; case tok::kw_asm: nextToken(); if (FormatTok->is(tok::l_brace)) { FormatTok->Type = TT_InlineASMBrace; nextToken(); while (FormatTok && FormatTok->isNot(tok::eof)) { if (FormatTok->is(tok::r_brace)) { FormatTok->Type = TT_InlineASMBrace; nextToken(); addUnwrappedLine(); break; } FormatTok->Finalized = true; nextToken(); } } break; case tok::kw_namespace: parseNamespace(); return; case tok::kw_inline: nextToken(); if (FormatTok->Tok.is(tok::kw_namespace)) { parseNamespace(); return; } break; case tok::kw_public: case tok::kw_protected: case tok::kw_private: if (Style.Language == FormatStyle::LK_Java || Style.Language == FormatStyle::LK_JavaScript) nextToken(); else parseAccessSpecifier(); return; case tok::kw_if: parseIfThenElse(); return; case tok::kw_for: case tok::kw_while: parseForOrWhileLoop(); return; case tok::kw_do: parseDoWhile(); return; case tok::kw_switch: parseSwitch(); return; case tok::kw_default: nextToken(); parseLabel(); return; case tok::kw_case: parseCaseLabel(); return; case tok::kw_try: case tok::kw___try: parseTryCatch(); return; case tok::kw_extern: nextToken(); if (FormatTok->Tok.is(tok::string_literal)) { nextToken(); if (FormatTok->Tok.is(tok::l_brace)) { parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false); addUnwrappedLine(); return; } } break; case tok::kw_export: if (Style.Language == FormatStyle::LK_JavaScript) { parseJavaScriptEs6ImportExport(); return; } break; case tok::identifier: if (FormatTok->is(TT_ForEachMacro)) { parseForOrWhileLoop(); return; } if (FormatTok->is(TT_MacroBlockBegin)) { parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true, /*MunchSemi=*/false); return; } if (Style.Language == FormatStyle::LK_JavaScript && FormatTok->is(Keywords.kw_import)) { parseJavaScriptEs6ImportExport(); return; } if (FormatTok->is(Keywords.kw_signals)) { nextToken(); if (FormatTok->is(tok::colon)) { nextToken(); addUnwrappedLine(); } return; } // In all other cases, parse the declaration. break; default: break; } do { switch (FormatTok->Tok.getKind()) { case tok::at: nextToken(); if (FormatTok->Tok.is(tok::l_brace)) parseBracedList(); break; case tok::kw_enum: // parseEnum falls through and does not yet add an unwrapped line as an // enum definition can start a structural element. parseEnum(); // This only applies for C++. if (Style.Language != FormatStyle::LK_Cpp) { addUnwrappedLine(); return; } break; case tok::kw_typedef: nextToken(); if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS, Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS)) parseEnum(); break; case tok::kw_struct: case tok::kw_union: case tok::kw_class: // parseRecord falls through and does not yet add an unwrapped line as a // record declaration or definition can start a structural element. parseRecord(); // This does not apply for Java and JavaScript. if (Style.Language == FormatStyle::LK_Java || Style.Language == FormatStyle::LK_JavaScript) { addUnwrappedLine(); return; } break; case tok::period: nextToken(); // In Java, classes have an implicit static member "class". if (Style.Language == FormatStyle::LK_Java && FormatTok && FormatTok->is(tok::kw_class)) nextToken(); if (Style.Language == FormatStyle::LK_JavaScript && FormatTok && FormatTok->Tok.getIdentifierInfo()) // JavaScript only has pseudo keywords, all keywords are allowed to // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6 nextToken(); break; case tok::semi: nextToken(); addUnwrappedLine(); return; case tok::r_brace: addUnwrappedLine(); return; case tok::l_paren: parseParens(); break; case tok::caret: nextToken(); if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isSimpleTypeSpecifier()) nextToken(); if (FormatTok->is(tok::l_paren)) parseParens(); if (FormatTok->is(tok::l_brace)) parseChildBlock(); break; case tok::l_brace: if (!tryToParseBracedList()) { // A block outside of parentheses must be the last part of a // structural element. // FIXME: Figure out cases where this is not true, and add projections // for them (the one we know is missing are lambdas). if (Style.BreakBeforeBraces != FormatStyle::BS_Attach) addUnwrappedLine(); FormatTok->Type = TT_FunctionLBrace; parseBlock(/*MustBeDeclaration=*/false); addUnwrappedLine(); return; } // Otherwise this was a braced init list, and the structural // element continues. break; case tok::kw_try: // We arrive here when parsing function-try blocks. parseTryCatch(); return; case tok::identifier: { if (FormatTok->is(TT_MacroBlockEnd)) { addUnwrappedLine(); return; } // Parse function literal unless 'function' is the first token in a line // in which case this should be treated as a free-standing function. if (Style.Language == FormatStyle::LK_JavaScript && FormatTok->is(Keywords.kw_function) && Line->Tokens.size() > 0) { tryToParseJSFunction(); break; } if ((Style.Language == FormatStyle::LK_JavaScript || Style.Language == FormatStyle::LK_Java) && FormatTok->is(Keywords.kw_interface)) { parseRecord(); addUnwrappedLine(); return; } StringRef Text = FormatTok->TokenText; nextToken(); if (Line->Tokens.size() == 1 && // JS doesn't have macros, and within classes colons indicate fields, // not labels. Style.Language != FormatStyle::LK_JavaScript) { if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) { parseLabel(); return; } // Recognize function-like macro usages without trailing semicolon as // well as free-standing macros like Q_OBJECT. bool FunctionLike = FormatTok->is(tok::l_paren); if (FunctionLike) parseParens(); bool FollowedByNewline = CommentsBeforeNextToken.empty() ? FormatTok->NewlinesBefore > 0 : CommentsBeforeNextToken.front()->NewlinesBefore > 0; if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) && tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) { addUnwrappedLine(); return; } } break; } case tok::equal: // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType // TT_JsFatArrow. The always start an expression or a child block if // followed by a curly. if (FormatTok->is(TT_JsFatArrow)) { nextToken(); if (FormatTok->is(tok::l_brace)) parseChildBlock(); break; } nextToken(); if (FormatTok->Tok.is(tok::l_brace)) { parseBracedList(); } break; case tok::l_square: parseSquare(); break; case tok::kw_new: parseNew(); break; default: nextToken(); break; } } while (!eof()); } bool UnwrappedLineParser::tryToParseLambda() { if (Style.Language != FormatStyle::LK_Cpp) { nextToken(); return false; } // FIXME: This is a dirty way to access the previous token. Find a better // solution. if (!Line->Tokens.empty() && (Line->Tokens.back().Tok->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new, tok::kw_delete) || Line->Tokens.back().Tok->closesScope() || Line->Tokens.back().Tok->isSimpleTypeSpecifier())) { nextToken(); return false; } assert(FormatTok->is(tok::l_square)); FormatToken &LSquare = *FormatTok; if (!tryToParseLambdaIntroducer()) return false; while (FormatTok->isNot(tok::l_brace)) { if (FormatTok->isSimpleTypeSpecifier()) { nextToken(); continue; } switch (FormatTok->Tok.getKind()) { case tok::l_brace: break; case tok::l_paren: parseParens(); break; case tok::amp: case tok::star: case tok::kw_const: case tok::comma: case tok::less: case tok::greater: case tok::identifier: case tok::numeric_constant: case tok::coloncolon: case tok::kw_mutable: nextToken(); break; case tok::arrow: FormatTok->Type = TT_LambdaArrow; nextToken(); break; default: return true; } } LSquare.Type = TT_LambdaLSquare; parseChildBlock(); return true; } bool UnwrappedLineParser::tryToParseLambdaIntroducer() { nextToken(); if (FormatTok->is(tok::equal)) { nextToken(); if (FormatTok->is(tok::r_square)) { nextToken(); return true; } if (FormatTok->isNot(tok::comma)) return false; nextToken(); } else if (FormatTok->is(tok::amp)) { nextToken(); if (FormatTok->is(tok::r_square)) { nextToken(); return true; } if (!FormatTok->isOneOf(tok::comma, tok::identifier)) { return false; } if (FormatTok->is(tok::comma)) nextToken(); } else if (FormatTok->is(tok::r_square)) { nextToken(); return true; } do { if (FormatTok->is(tok::amp)) nextToken(); if (!FormatTok->isOneOf(tok::identifier, tok::kw_this)) return false; nextToken(); if (FormatTok->is(tok::ellipsis)) nextToken(); if (FormatTok->is(tok::comma)) { nextToken(); } else if (FormatTok->is(tok::r_square)) { nextToken(); return true; } else { return false; } } while (!eof()); return false; } void UnwrappedLineParser::tryToParseJSFunction() { nextToken(); // Consume function name. if (FormatTok->is(tok::identifier)) nextToken(); if (FormatTok->isNot(tok::l_paren)) return; // Parse formal parameter list. parseParens(); if (FormatTok->is(tok::colon)) { // Parse a type definition. nextToken(); // Eat the type declaration. For braced inline object types, balance braces, // otherwise just parse until finding an l_brace for the function body. if (FormatTok->is(tok::l_brace)) tryToParseBracedList(); else while (FormatTok->isNot(tok::l_brace) && !eof()) nextToken(); } parseChildBlock(); } bool UnwrappedLineParser::tryToParseBracedList() { if (FormatTok->BlockKind == BK_Unknown) calculateBraceTypes(); assert(FormatTok->BlockKind != BK_Unknown); if (FormatTok->BlockKind == BK_Block) return false; parseBracedList(); return true; } bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) { bool HasError = false; nextToken(); // FIXME: Once we have an expression parser in the UnwrappedLineParser, // replace this by using parseAssigmentExpression() inside. do { if (Style.Language == FormatStyle::LK_JavaScript) { if (FormatTok->is(Keywords.kw_function)) { tryToParseJSFunction(); continue; } if (FormatTok->is(TT_JsFatArrow)) { nextToken(); // Fat arrows can be followed by simple expressions or by child blocks // in curly braces. if (FormatTok->is(tok::l_brace)) { parseChildBlock(); continue; } } } switch (FormatTok->Tok.getKind()) { case tok::caret: nextToken(); if (FormatTok->is(tok::l_brace)) { parseChildBlock(); } break; case tok::l_square: tryToParseLambda(); break; case tok::l_brace: // Assume there are no blocks inside a braced init list apart // from the ones we explicitly parse out (like lambdas). FormatTok->BlockKind = BK_BracedInit; parseBracedList(); break; case tok::l_paren: parseParens(); // JavaScript can just have free standing methods and getters/setters in // object literals. Detect them by a "{" following ")". if (Style.Language == FormatStyle::LK_JavaScript) { if (FormatTok->is(tok::l_brace)) parseChildBlock(); break; } break; case tok::r_brace: nextToken(); return !HasError; case tok::semi: HasError = true; if (!ContinueOnSemicolons) return !HasError; nextToken(); break; case tok::comma: nextToken(); break; default: nextToken(); break; } } while (!eof()); return false; } void UnwrappedLineParser::parseParens() { assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected."); nextToken(); do { switch (FormatTok->Tok.getKind()) { case tok::l_paren: parseParens(); if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace)) parseChildBlock(); break; case tok::r_paren: nextToken(); return; case tok::r_brace: // A "}" inside parenthesis is an error if there wasn't a matching "{". return; case tok::l_square: tryToParseLambda(); break; case tok::l_brace: if (!tryToParseBracedList()) parseChildBlock(); break; case tok::at: nextToken(); if (FormatTok->Tok.is(tok::l_brace)) parseBracedList(); break; case tok::identifier: if (Style.Language == FormatStyle::LK_JavaScript && FormatTok->is(Keywords.kw_function)) tryToParseJSFunction(); else nextToken(); break; default: nextToken(); break; } } while (!eof()); } void UnwrappedLineParser::parseSquare() { assert(FormatTok->Tok.is(tok::l_square) && "'[' expected."); if (tryToParseLambda()) return; do { switch (FormatTok->Tok.getKind()) { case tok::l_paren: parseParens(); break; case tok::r_square: nextToken(); return; case tok::r_brace: // A "}" inside parenthesis is an error if there wasn't a matching "{". return; case tok::l_square: parseSquare(); break; case tok::l_brace: { if (!tryToParseBracedList()) parseChildBlock(); break; } case tok::at: nextToken(); if (FormatTok->Tok.is(tok::l_brace)) parseBracedList(); break; default: nextToken(); break; } } while (!eof()); } void UnwrappedLineParser::parseIfThenElse() { assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected"); nextToken(); if (FormatTok->Tok.is(tok::l_paren)) parseParens(); bool NeedsUnwrappedLine = false; if (FormatTok->Tok.is(tok::l_brace)) { CompoundStatementIndenter Indenter(this, Style, Line->Level); parseBlock(/*MustBeDeclaration=*/false); if (Style.BreakBeforeBraces == FormatStyle::BS_Allman || Style.BreakBeforeBraces == FormatStyle::BS_GNU) { addUnwrappedLine(); } else { NeedsUnwrappedLine = true; } } else { addUnwrappedLine(); ++Line->Level; parseStructuralElement(); --Line->Level; } if (FormatTok->Tok.is(tok::kw_else)) { if (Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) addUnwrappedLine(); nextToken(); if (FormatTok->Tok.is(tok::l_brace)) { CompoundStatementIndenter Indenter(this, Style, Line->Level); parseBlock(/*MustBeDeclaration=*/false); addUnwrappedLine(); } else if (FormatTok->Tok.is(tok::kw_if)) { parseIfThenElse(); } else { addUnwrappedLine(); ++Line->Level; parseStructuralElement(); --Line->Level; } } else if (NeedsUnwrappedLine) { addUnwrappedLine(); } } void UnwrappedLineParser::parseTryCatch() { assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected"); nextToken(); bool NeedsUnwrappedLine = false; if (FormatTok->is(tok::colon)) { // We are in a function try block, what comes is an initializer list. nextToken(); while (FormatTok->is(tok::identifier)) { nextToken(); if (FormatTok->is(tok::l_paren)) parseParens(); if (FormatTok->is(tok::comma)) nextToken(); } } // Parse try with resource. if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) { parseParens(); } if (FormatTok->is(tok::l_brace)) { CompoundStatementIndenter Indenter(this, Style, Line->Level); parseBlock(/*MustBeDeclaration=*/false); if (Style.BreakBeforeBraces == FormatStyle::BS_Allman || Style.BreakBeforeBraces == FormatStyle::BS_GNU || Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) { addUnwrappedLine(); } else { NeedsUnwrappedLine = true; } } else if (!FormatTok->is(tok::kw_catch)) { // The C++ standard requires a compound-statement after a try. // If there's none, we try to assume there's a structuralElement // and try to continue. addUnwrappedLine(); ++Line->Level; parseStructuralElement(); --Line->Level; } while (1) { if (FormatTok->is(tok::at)) nextToken(); if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except, tok::kw___finally) || ((Style.Language == FormatStyle::LK_Java || Style.Language == FormatStyle::LK_JavaScript) && FormatTok->is(Keywords.kw_finally)) || (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) || FormatTok->Tok.isObjCAtKeyword(tok::objc_finally)))) break; nextToken(); while (FormatTok->isNot(tok::l_brace)) { if (FormatTok->is(tok::l_paren)) { parseParens(); continue; } if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof)) return; nextToken(); } NeedsUnwrappedLine = false; CompoundStatementIndenter Indenter(this, Style, Line->Level); parseBlock(/*MustBeDeclaration=*/false); if (Style.BreakBeforeBraces == FormatStyle::BS_Allman || Style.BreakBeforeBraces == FormatStyle::BS_GNU || Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) { addUnwrappedLine(); } else { NeedsUnwrappedLine = true; } } if (NeedsUnwrappedLine) { addUnwrappedLine(); } } void UnwrappedLineParser::parseNamespace() { assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected"); const FormatToken &InitialToken = *FormatTok; nextToken(); if (FormatTok->Tok.is(tok::identifier)) nextToken(); if (FormatTok->Tok.is(tok::l_brace)) { if (ShouldBreakBeforeBrace(Style, InitialToken)) addUnwrappedLine(); bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All || (Style.NamespaceIndentation == FormatStyle::NI_Inner && DeclarationScopeStack.size() > 1); parseBlock(/*MustBeDeclaration=*/true, AddLevel); // Munch the semicolon after a namespace. This is more common than one would // think. Puttin the semicolon into its own line is very ugly. if (FormatTok->Tok.is(tok::semi)) nextToken(); addUnwrappedLine(); } // FIXME: Add error handling. } void UnwrappedLineParser::parseNew() { assert(FormatTok->is(tok::kw_new) && "'new' expected"); nextToken(); if (Style.Language != FormatStyle::LK_Java) return; // In Java, we can parse everything up to the parens, which aren't optional. do { // There should not be a ;, { or } before the new's open paren. if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace)) return; // Consume the parens. if (FormatTok->is(tok::l_paren)) { parseParens(); // If there is a class body of an anonymous class, consume that as child. if (FormatTok->is(tok::l_brace)) parseChildBlock(); return; } nextToken(); } while (!eof()); } void UnwrappedLineParser::parseForOrWhileLoop() { assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) && "'for', 'while' or foreach macro expected"); nextToken(); if (FormatTok->Tok.is(tok::l_paren)) parseParens(); if (FormatTok->Tok.is(tok::l_brace)) { CompoundStatementIndenter Indenter(this, Style, Line->Level); parseBlock(/*MustBeDeclaration=*/false); addUnwrappedLine(); } else { addUnwrappedLine(); ++Line->Level; parseStructuralElement(); --Line->Level; } } void UnwrappedLineParser::parseDoWhile() { assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected"); nextToken(); if (FormatTok->Tok.is(tok::l_brace)) { CompoundStatementIndenter Indenter(this, Style, Line->Level); parseBlock(/*MustBeDeclaration=*/false); if (Style.BreakBeforeBraces == FormatStyle::BS_GNU) addUnwrappedLine(); } else { addUnwrappedLine(); ++Line->Level; parseStructuralElement(); --Line->Level; } // FIXME: Add error handling. if (!FormatTok->Tok.is(tok::kw_while)) { addUnwrappedLine(); return; } nextToken(); parseStructuralElement(); } void UnwrappedLineParser::parseLabel() { nextToken(); unsigned OldLineLevel = Line->Level; if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0)) --Line->Level; if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) { CompoundStatementIndenter Indenter(this, Style, Line->Level); parseBlock(/*MustBeDeclaration=*/false); if (FormatTok->Tok.is(tok::kw_break)) { // "break;" after "}" on its own line only for BS_Allman and BS_GNU if (Style.BreakBeforeBraces == FormatStyle::BS_Allman || Style.BreakBeforeBraces == FormatStyle::BS_GNU) { addUnwrappedLine(); } parseStructuralElement(); } addUnwrappedLine(); } else { if (FormatTok->is(tok::semi)) nextToken(); addUnwrappedLine(); } Line->Level = OldLineLevel; } void UnwrappedLineParser::parseCaseLabel() { assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected"); // FIXME: fix handling of complex expressions here. do { nextToken(); } while (!eof() && !FormatTok->Tok.is(tok::colon)); parseLabel(); } void UnwrappedLineParser::parseSwitch() { assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected"); nextToken(); if (FormatTok->Tok.is(tok::l_paren)) parseParens(); if (FormatTok->Tok.is(tok::l_brace)) { CompoundStatementIndenter Indenter(this, Style, Line->Level); parseBlock(/*MustBeDeclaration=*/false); addUnwrappedLine(); } else { addUnwrappedLine(); ++Line->Level; parseStructuralElement(); --Line->Level; } } void UnwrappedLineParser::parseAccessSpecifier() { nextToken(); // Understand Qt's slots. if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots)) nextToken(); // Otherwise, we don't know what it is, and we'd better keep the next token. if (FormatTok->Tok.is(tok::colon)) nextToken(); addUnwrappedLine(); } void UnwrappedLineParser::parseEnum() { // Won't be 'enum' for NS_ENUMs. if (FormatTok->Tok.is(tok::kw_enum)) nextToken(); // Eat up enum class ... if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct)) nextToken(); while (FormatTok->Tok.getIdentifierInfo() || FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less, tok::greater, tok::comma, tok::question)) { nextToken(); // We can have macros or attributes in between 'enum' and the enum name. if (FormatTok->is(tok::l_paren)) parseParens(); if (FormatTok->is(tok::identifier)) { nextToken(); // If there are two identifiers in a row, this is likely an elaborate // return type. In Java, this can be "implements", etc. if (Style.Language == FormatStyle::LK_Cpp && FormatTok->is(tok::identifier)) return; } } // Just a declaration or something is wrong. if (FormatTok->isNot(tok::l_brace)) return; FormatTok->BlockKind = BK_Block; if (Style.Language == FormatStyle::LK_Java) { // Java enums are different. parseJavaEnumBody(); return; } else if (Style.Language == FormatStyle::LK_Proto) { parseBlock(/*MustBeDeclaration=*/true); return; } // Parse enum body. bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true); if (HasError) { if (FormatTok->is(tok::semi)) nextToken(); addUnwrappedLine(); } // There is no addUnwrappedLine() here so that we fall through to parsing a // structural element afterwards. Thus, in "enum A {} n, m;", // "} n, m;" will end up in one unwrapped line. } void UnwrappedLineParser::parseJavaEnumBody() { // Determine whether the enum is simple, i.e. does not have a semicolon or // constants with class bodies. Simple enums can be formatted like braced // lists, contracted to a single line, etc. unsigned StoredPosition = Tokens->getPosition(); bool IsSimple = true; FormatToken *Tok = Tokens->getNextToken(); while (Tok) { if (Tok->is(tok::r_brace)) break; if (Tok->isOneOf(tok::l_brace, tok::semi)) { IsSimple = false; break; } // FIXME: This will also mark enums with braces in the arguments to enum // constants as "not simple". This is probably fine in practice, though. Tok = Tokens->getNextToken(); } FormatTok = Tokens->setPosition(StoredPosition); if (IsSimple) { parseBracedList(); addUnwrappedLine(); return; } // Parse the body of a more complex enum. // First add a line for everything up to the "{". nextToken(); addUnwrappedLine(); ++Line->Level; // Parse the enum constants. while (FormatTok) { if (FormatTok->is(tok::l_brace)) { // Parse the constant's class body. parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true, /*MunchSemi=*/false); } else if (FormatTok->is(tok::l_paren)) { parseParens(); } else if (FormatTok->is(tok::comma)) { nextToken(); addUnwrappedLine(); } else if (FormatTok->is(tok::semi)) { nextToken(); addUnwrappedLine(); break; } else if (FormatTok->is(tok::r_brace)) { addUnwrappedLine(); break; } else { nextToken(); } } // Parse the class body after the enum's ";" if any. parseLevel(/*HasOpeningBrace=*/true); nextToken(); --Line->Level; addUnwrappedLine(); } void UnwrappedLineParser::parseRecord() { const FormatToken &InitialToken = *FormatTok; nextToken(); // The actual identifier can be a nested name specifier, and in macros // it is often token-pasted. while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash, tok::kw___attribute, tok::kw___declspec, tok::kw_alignas) || ((Style.Language == FormatStyle::LK_Java || Style.Language == FormatStyle::LK_JavaScript) && FormatTok->isOneOf(tok::period, tok::comma))) { bool IsNonMacroIdentifier = FormatTok->is(tok::identifier) && FormatTok->TokenText != FormatTok->TokenText.upper(); nextToken(); // We can have macros or attributes in between 'class' and the class name. if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren)) parseParens(); } // Note that parsing away template declarations here leads to incorrectly // accepting function declarations as record declarations. // In general, we cannot solve this problem. Consider: // class A<int> B() {} // which can be a function definition or a class definition when B() is a // macro. If we find enough real-world cases where this is a problem, we // can parse for the 'template' keyword in the beginning of the statement, // and thus rule out the record production in case there is no template // (this would still leave us with an ambiguity between template function // and class declarations). if (FormatTok->isOneOf(tok::colon, tok::less)) { while (!eof()) { if (FormatTok->is(tok::l_brace)) { calculateBraceTypes(/*ExpectClassBody=*/true); if (!tryToParseBracedList()) break; } if (FormatTok->Tok.is(tok::semi)) return; nextToken(); } } if (FormatTok->Tok.is(tok::l_brace)) { if (ShouldBreakBeforeBrace(Style, InitialToken)) addUnwrappedLine(); parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true, /*MunchSemi=*/false); } // There is no addUnwrappedLine() here so that we fall through to parsing a // structural element afterwards. Thus, in "class A {} n, m;", // "} n, m;" will end up in one unwrapped line. } void UnwrappedLineParser::parseObjCProtocolList() { assert(FormatTok->Tok.is(tok::less) && "'<' expected."); do nextToken(); while (!eof() && FormatTok->Tok.isNot(tok::greater)); nextToken(); // Skip '>'. } void UnwrappedLineParser::parseObjCUntilAtEnd() { do { if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) { nextToken(); addUnwrappedLine(); break; } if (FormatTok->is(tok::l_brace)) { parseBlock(/*MustBeDeclaration=*/false); // In ObjC interfaces, nothing should be following the "}". addUnwrappedLine(); } else if (FormatTok->is(tok::r_brace)) { // Ignore stray "}". parseStructuralElement doesn't consume them. nextToken(); addUnwrappedLine(); } else { parseStructuralElement(); } } while (!eof()); } void UnwrappedLineParser::parseObjCInterfaceOrImplementation() { nextToken(); nextToken(); // interface name // @interface can be followed by either a base class, or a category. if (FormatTok->Tok.is(tok::colon)) { nextToken(); nextToken(); // base class name } else if (FormatTok->Tok.is(tok::l_paren)) // Skip category, if present. parseParens(); if (FormatTok->Tok.is(tok::less)) parseObjCProtocolList(); if (FormatTok->Tok.is(tok::l_brace)) { if (Style.BreakBeforeBraces == FormatStyle::BS_Allman || Style.BreakBeforeBraces == FormatStyle::BS_GNU) addUnwrappedLine(); parseBlock(/*MustBeDeclaration=*/true); } // With instance variables, this puts '}' on its own line. Without instance // variables, this ends the @interface line. addUnwrappedLine(); parseObjCUntilAtEnd(); } void UnwrappedLineParser::parseObjCProtocol() { nextToken(); nextToken(); // protocol name if (FormatTok->Tok.is(tok::less)) parseObjCProtocolList(); // Check for protocol declaration. if (FormatTok->Tok.is(tok::semi)) { nextToken(); return addUnwrappedLine(); } addUnwrappedLine(); parseObjCUntilAtEnd(); } void UnwrappedLineParser::parseJavaScriptEs6ImportExport() { assert(FormatTok->isOneOf(Keywords.kw_import, tok::kw_export)); nextToken(); // Consume the "default" in "export default class/function". if (FormatTok->is(tok::kw_default)) nextToken(); // Consume "function" and "default function", so that these get parsed as // free-standing JS functions, i.e. do not require a trailing semicolon. if (FormatTok->is(Keywords.kw_function)) { nextToken(); return; } if (FormatTok->isOneOf(tok::kw_const, tok::kw_class, tok::kw_enum, Keywords.kw_let, Keywords.kw_var)) return; // Fall through to parsing the corresponding structure. if (FormatTok->is(tok::l_brace)) { FormatTok->BlockKind = BK_Block; parseBracedList(); } while (!eof() && FormatTok->isNot(tok::semi) && FormatTok->isNot(tok::l_brace)) { nextToken(); } } LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line, StringRef Prefix = "") { llvm::dbgs() << Prefix << "Line(" << Line.Level << ")" << (Line.InPPDirective ? " MACRO" : "") << ": "; for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), E = Line.Tokens.end(); I != E; ++I) { llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] "; } for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(), E = Line.Tokens.end(); I != E; ++I) { const UnwrappedLineNode &Node = *I; for (SmallVectorImpl<UnwrappedLine>::const_iterator I = Node.Children.begin(), E = Node.Children.end(); I != E; ++I) { printDebugInfo(*I, "\nChild: "); } } llvm::dbgs() << "\n"; } void UnwrappedLineParser::addUnwrappedLine() { if (Line->Tokens.empty()) return; DEBUG({ if (CurrentLines == &Lines) printDebugInfo(*Line); }); CurrentLines->push_back(std::move(*Line)); Line->Tokens.clear(); if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) { CurrentLines->append( std::make_move_iterator(PreprocessorDirectives.begin()), std::make_move_iterator(PreprocessorDirectives.end())); PreprocessorDirectives.clear(); } } bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); } bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) { return (Line->InPPDirective || FormatTok.HasUnescapedNewline) && FormatTok.NewlinesBefore > 0; } void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) { bool JustComments = Line->Tokens.empty(); for (SmallVectorImpl<FormatToken *>::const_iterator I = CommentsBeforeNextToken.begin(), E = CommentsBeforeNextToken.end(); I != E; ++I) { if (isOnNewLine(**I) && JustComments) addUnwrappedLine(); pushToken(*I); } if (NewlineBeforeNext && JustComments) addUnwrappedLine(); CommentsBeforeNextToken.clear(); } void UnwrappedLineParser::nextToken() { if (eof()) return; flushComments(isOnNewLine(*FormatTok)); pushToken(FormatTok); readToken(); } void UnwrappedLineParser::readToken() { bool CommentsInCurrentLine = true; do { FormatTok = Tokens->getNextToken(); assert(FormatTok); while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) && (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) { // If there is an unfinished unwrapped line, we flush the preprocessor // directives only after that unwrapped line was finished later. bool SwitchToPreprocessorLines = !Line->Tokens.empty(); ScopedLineState BlockState(*this, SwitchToPreprocessorLines); // Comments stored before the preprocessor directive need to be output // before the preprocessor directive, at the same level as the // preprocessor directive, as we consider them to apply to the directive. flushComments(isOnNewLine(*FormatTok)); parsePPDirective(); } while (FormatTok->Type == TT_ConflictStart || FormatTok->Type == TT_ConflictEnd || FormatTok->Type == TT_ConflictAlternative) { if (FormatTok->Type == TT_ConflictStart) { conditionalCompilationStart(/*Unreachable=*/false); } else if (FormatTok->Type == TT_ConflictAlternative) { conditionalCompilationAlternative(); } else if (FormatTok->Type == TT_ConflictEnd) { conditionalCompilationEnd(); } FormatTok = Tokens->getNextToken(); FormatTok->MustBreakBefore = true; } if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) && !Line->InPPDirective) { continue; } if (!FormatTok->Tok.is(tok::comment)) return; if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) { CommentsInCurrentLine = false; } if (CommentsInCurrentLine) { pushToken(FormatTok); } else { CommentsBeforeNextToken.push_back(FormatTok); } } while (!eof()); } void UnwrappedLineParser::pushToken(FormatToken *Tok) { Line->Tokens.push_back(UnwrappedLineNode(Tok)); if (MustBreakBeforeNextToken) { Line->Tokens.back().Tok->MustBreakBefore = true; MustBreakBeforeNextToken = false; } } } // end namespace format } // end namespace clang
; Top-hole Golf ; Copyright 2020-2021 Matthew Clarke !to "splash.o",cbm !source "../core/labels.asm" !source "../core/mymacros.asm" !source "../core/vic_ii.asm" *= end_of_core !zone { splash_s_init +utils_m_enable_bitmap_mode +clr splash_v_must_exit ; Copy pixel data to bitmap. ; 40*25*8 = 8000 bytes. ; = 32*256... ; Source = MATHS0/1, destination = MATHS2/3. lda #<splash_c_PIXELS sta MATHS0 lda #>splash_c_PIXELS sta MATHS1 lda #<gfxs_c_BITMAP_BASE sta MATHS2 lda #>gfxs_c_BITMAP_BASE sta MATHS3 ldx #0 ldy #0 - lda (MATHS0),y sta (MATHS2),y iny bne - inx cpx #32 beq .colors inc MATHS1 inc MATHS3 jmp - .colors ldx #0 - lda splash_c_VIDEO_RAM,x sta gfxs_c_DISPLAY_BASE,x lda splash_c_VIDEO_RAM+250,x sta gfxs_c_DISPLAY_BASE+250,x lda splash_c_VIDEO_RAM+500,x sta gfxs_c_DISPLAY_BASE+500,x lda splash_c_VIDEO_RAM+750,x sta gfxs_c_DISPLAY_BASE+750,x inx cpx #250 bne - lda #BLACK sta EXTCOL jsr interrupts_s_install - lda splash_v_must_exit +branch_if_false - rts ; end sub splash_s_init } ; !zone ; ***************** ; *** CONSTANTS *** ; ***************** !source "../../assets/pictures/mysplash.asm" ; ***************** ; *** VARIABLES *** ; ***************** splash_v_must_exit !byte 0 ; ******************* ; ****** MACROS ***** ; ******************* ; ******************* ; *** SUBROUTINES *** ; ******************* ; ************************************************** !zone { splash_s_update ; Play music (?!) ; Update any graphical effects (?!) ; Listen for button/key press... ldx #joy_c_PORT2 +joy_m_is_fire bne .end jsr interrupts_s_uninstall inc splash_v_must_exit .end rts ; end sub splash_s_update } ; !zone ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** ; ************************************************** !source "interrupts.asm"
; A123746: Numerators of partial sums of a series for 1/sqrt(2). ; Submitted by Christian Krause ; 1,1,7,9,107,151,835,1241,26291,40427,207897,327615,3296959,5293843,26189947,42685049,1666461763,2749521971,13266871709,22115585443,211386315749,355490397193,1684973959237,2855358497999,53747636888759,91693947972799,428765608509709,735847502916411,6842866348426343,11806528540631371,54617650510329323,94690664981431737,6976514629282926435,12148172150061786435,55705948969057289925,97388613211031724171,889737040757462988169,1561207760972972700109,7106408624978548469761,12511753820632157438547 seq $0,91520 ; Expansion of 1 / ((1 - 4*x) * sqrt(1 + 4*x)) in powers of x. lpb $0 dif $0,2 lpe
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %r15 push %r9 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x82d5, %rbp sub $58043, %rdx movw $0x6162, (%rbp) nop nop cmp $11065, %rbp lea addresses_D_ht+0x19989, %r14 xor $31096, %r15 movb $0x61, (%r14) nop nop nop nop nop add %r14, %r14 lea addresses_normal_ht+0x10755, %rsi lea addresses_WC_ht+0x114b5, %rdi nop and %r10, %r10 mov $90, %rcx rep movsw nop nop cmp %rsi, %rsi lea addresses_WT_ht+0x1d545, %rsi lea addresses_D_ht+0x13f0f, %rdi nop nop and %r9, %r9 mov $32, %rcx rep movsq add $53008, %r14 lea addresses_D_ht+0x156d5, %rsi lea addresses_UC_ht+0x96d5, %rdi nop nop nop cmp %r9, %r9 mov $68, %rcx rep movsb nop nop add %rdi, %rdi lea addresses_A_ht+0x1bad5, %rdi nop nop nop nop nop inc %r9 movb (%rdi), %dl nop nop add %r14, %r14 lea addresses_A_ht+0x171e5, %rcx nop nop nop nop nop cmp %r10, %r10 mov (%rcx), %bp nop nop nop and $50804, %rbp lea addresses_normal_ht+0x17cd5, %r14 nop nop cmp %rbp, %rbp mov (%r14), %r9 nop xor $26029, %r14 lea addresses_UC_ht+0x1065d, %r9 clflush (%r9) nop nop nop nop nop sub $47789, %r14 vmovups (%r9), %ymm3 vextracti128 $0, %ymm3, %xmm3 vpextrq $0, %xmm3, %rdi add %r14, %r14 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r9 pop %r15 pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %rbp push %rbx push %rcx push %rdi push %rdx // Store mov $0x7082450000000fb5, %rdi nop nop nop sub $5054, %rcx mov $0x5152535455565758, %rdx movq %rdx, %xmm4 movups %xmm4, (%rdi) xor %rdx, %rdx // Store mov $0x3e9deb00000002d5, %rbp sub %r11, %r11 mov $0x5152535455565758, %rdx movq %rdx, %xmm0 vmovups %ymm0, (%rbp) nop nop nop and $42455, %r11 // Store lea addresses_D+0x15f55, %r11 xor %rbp, %rbp mov $0x5152535455565758, %r13 movq %r13, %xmm7 vmovntdq %ymm7, (%r11) nop nop nop dec %rdi // Store mov $0x5f5, %rdx nop add %r11, %r11 movl $0x51525354, (%rdx) nop nop nop nop cmp %r13, %r13 // Store mov $0xa71, %rcx nop nop nop nop sub %rdi, %rdi movw $0x5152, (%rcx) nop nop xor %rcx, %rcx // Load lea addresses_A+0x1c2d5, %rbp nop nop nop nop cmp %r11, %r11 vmovaps (%rbp), %ymm5 vextracti128 $1, %ymm5, %xmm5 vpextrq $1, %xmm5, %rbx nop nop nop cmp $51188, %rdx // Faulty Load lea addresses_A+0x1c2d5, %rbx nop nop nop nop cmp %rbp, %rbp mov (%rbx), %r11d lea oracles, %rcx and $0xff, %r11 shlq $12, %r11 mov (%rcx,%r11,1), %r11 pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A', 'NT': True, 'AVXalign': False, 'size': 2, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 3}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 7}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D', 'NT': True, 'AVXalign': False, 'size': 32, 'congruent': 5}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 5}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 2}} {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A', 'NT': False, 'AVXalign': True, 'size': 32, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 2}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_normal_ht'}, 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_WC_ht'}} {'OP': 'REPM', 'src': {'same': True, 'congruent': 4, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_D_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 11}} {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 3}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 9}} {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 2}} {'58': 2} 58 58 */
;***************************************************************** ;* - Description: Device definition file for RC Calibration ;* - File: t24.asm ;* - AppNote: AVR053 - Production calibration of the ;* RC oscillator ;* ;* - Author: Atmel Corporation: http://www.atmel.com ;* Support email: avr@atmel.com ;* ;* $Name$ ;* $Revision: 56 $ ;* $RCSfile$ ;* $Date: 2006-02-16 17:44:45 +0100 (to, 16 feb 2006) $ ;***************************************************************** .include "tn24def.inc" .include "Common\memoryMap.inc" .include "Device specific\t24_family_pinout.inc" .EQU OSC_VER = 5 .equ TCCR0 = TCCR0B .equ TIFR = TIFR0 .equ EEMWE = EEMPE .equ EEWE = EEPE
;/* ; FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd. ; All rights reserved ; ; VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. ; ; This file is part of the FreeRTOS distribution. ; ; FreeRTOS is free software; you can redistribute it and/or modify it under ; the terms of the GNU General Public License (version 2) as published by the ; Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. ; ; *************************************************************************** ; >>! NOTE: The modification to the GPL is included to allow you to !<< ; >>! distribute a combined work that includes FreeRTOS without being !<< ; >>! obliged to provide the source code for proprietary components !<< ; >>! outside of the FreeRTOS kernel. !<< ; *************************************************************************** ; ; FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY ; WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS ; FOR A PARTICULAR PURPOSE. Full license text is available on the following ; link: http://www.freertos.org/a00114.html ; ; *************************************************************************** ; * * ; * FreeRTOS provides completely free yet professionally developed, * ; * robust, strictly quality controlled, supported, and cross * ; * platform software that is more than just the market leader, it * ; * is the industry's de facto standard. * ; * * ; * Help yourself get started quickly while simultaneously helping * ; * to support the FreeRTOS project by purchasing a FreeRTOS * ; * tutorial book, reference manual, or both: * ; * http://www.FreeRTOS.org/Documentation * ; * * ; *************************************************************************** ; ; http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading ; the FAQ page "My application does not run, what could be wrong?". Have you ; defined configASSERT()? ; ; http://www.FreeRTOS.org/support - In return for receiving this top quality ; embedded software for free we request you assist our global community by ; participating in the support forum. ; ; http://www.FreeRTOS.org/training - Investing in training allows your team to ; be as productive as possible as early as possible. Now you can receive ; FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers ; Ltd, and the world's leading authority on the world's leading RTOS. ; ; http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, ; including FreeRTOS+Trace - an indispensable productivity tool, a DOS ; compatible FAT file system, and our tiny thread aware UDP/IP stack. ; ; http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. ; Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. ; ; http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High ; Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS ; licenses offer ticketed support, indemnification and commercial middleware. ; ; http://www.SafeRTOS.com - High Integrity Systems also provide a safety ; engineered and independently SIL3 certified version for use in safety and ; mission critical applications that require provable dependability. ; ; 1 tab == 4 spaces! ;*/ .thumb .ref pxCurrentTCB .ref vTaskSwitchContext .ref ulMaxSyscallInterruptPriority .def xPortPendSVHandler .def ulPortGetIPSR .def vPortSVCHandler .def vPortStartFirstTask .def vPortEnableVFP NVICOffsetConst: .word 0xE000ED08 CPACRConst: .word 0xE000ED88 pxCurrentTCBConst: .word pxCurrentTCB ulMaxSyscallInterruptPriorityConst: .word ulMaxSyscallInterruptPriority ; ----------------------------------------------------------- .align 4 ulPortGetIPSR: .asmfunc mrs r0, ipsr bx r14 .endasmfunc ; ----------------------------------------------------------- .align 4 vPortSetInterruptMask: .asmfunc push {r0} ldr r0, ulMaxSyscallInterruptPriorityConst msr basepri, r0 pop {r0} bx r14 .endasmfunc ; ----------------------------------------------------------- .align 4 xPortPendSVHandler: .asmfunc mrs r0, psp isb ;/* Get the location of the current TCB. */ ldr r3, pxCurrentTCBConst ldr r2, [r3] ;/* Is the task using the FPU context? If so, push high vfp registers. */ tst r14, #0x10 it eq vstmdbeq r0!, {s16-s31} ;/* Save the core registers. */ stmdb r0!, {r4-r11, r14} ;/* Save the new top of stack into the first member of the TCB. */ str r0, [r2] stmdb sp!, {r3} ldr r0, ulMaxSyscallInterruptPriorityConst ldr r1, [r0] msr basepri, r1 dsb isb bl vTaskSwitchContext mov r0, #0 msr basepri, r0 ldmia sp!, {r3} ;/* The first item in pxCurrentTCB is the task top of stack. */ ldr r1, [r3] ldr r0, [r1] ;/* Pop the core registers. */ ldmia r0!, {r4-r11, r14} ;/* Is the task using the FPU context? If so, pop the high vfp registers ;too. */ tst r14, #0x10 it eq vldmiaeq r0!, {s16-s31} msr psp, r0 isb bx r14 .endasmfunc ; ----------------------------------------------------------- .align 4 vPortSVCHandler: .asmfunc ;/* Get the location of the current TCB. */ ldr r3, pxCurrentTCBConst ldr r1, [r3] ldr r0, [r1] ;/* Pop the core registers. */ ldmia r0!, {r4-r11, r14} msr psp, r0 isb mov r0, #0 msr basepri, r0 bx r14 .endasmfunc ; ----------------------------------------------------------- .align 4 vPortStartFirstTask: .asmfunc ;/* Use the NVIC offset register to locate the stack. */ ldr r0, NVICOffsetConst ldr r0, [r0] ldr r0, [r0] ;/* Set the msp back to the start of the stack. */ msr msp, r0 ;/* Call SVC to start the first task. */ cpsie i cpsie f dsb isb svc #0 .endasmfunc ; ----------------------------------------------------------- .align 4 vPortEnableVFP: .asmfunc ;/* The FPU enable bits are in the CPACR. */ ldr.w r0, CPACRConst ldr r1, [r0] ;/* Enable CP10 and CP11 coprocessors, then save back. */ orr r1, r1, #( 0xf << 20 ) str r1, [r0] bx r14 .endasmfunc .end ; -----------------------------------------------------------
; int isblank(int c) SECTION code_clib SECTION code_ctype PUBLIC _isblank EXTERN _isblank_fastcall _isblank: pop af pop hl push hl push af jp _isblank_fastcall
; A049480: a(n) = (2*n-1)*(n^2 -n +6)/6. ; 1,4,10,21,39,66,104,155,221,304,406,529,675,846,1044,1271,1529,1820,2146,2509,2911,3354,3840,4371,4949,5576,6254,6985,7771,8614,9516,10479,11505,12596,13754,14981,16279,17650,19096,20619,22221,23904,25670,27521,29459,31486,33604,35815,38121,40524,43026,45629,48335,51146,54064,57091,60229,63480,66846,70329,73931,77654,81500,85471,89569,93796,98154,102645,107271,112034,116936,121979,127165,132496,137974,143601,149379,155310,161396,167639,174041,180604,187330,194221,201279,208506,215904,223475,231221,239144,247246,255529,263995,272646,281484,290511,299729,309140,318746,328549,338551,348754,359160,369771,380589,391616,402854,414305,425971,437854,449956,462279,474825,487596,500594,513821,527279,540970,554896,569059,583461,598104,612990,628121,643499,659126,675004,691135,707521,724164,741066,758229,775655,793346,811304,829531,848029,866800,885846,905169,924771,944654,964820,985271,1006009,1027036,1048354,1069965,1091871,1114074,1136576,1159379,1182485,1205896,1229614,1253641,1277979,1302630,1327596,1352879,1378481,1404404,1430650,1457221,1484119,1511346,1538904,1566795,1595021,1623584,1652486,1681729,1711315,1741246,1771524,1802151,1833129,1864460,1896146,1928189,1960591,1993354,2026480,2059971,2093829,2128056,2162654,2197625,2232971,2268694,2304796,2341279,2378145,2415396,2453034,2491061,2529479,2568290,2607496,2647099,2687101,2727504,2768310,2809521,2851139,2893166,2935604,2978455,3021721,3065404,3109506,3154029,3198975,3244346,3290144,3336371,3383029,3430120,3477646,3525609,3574011,3622854,3672140,3721871,3772049,3822676,3873754,3925285,3977271,4029714,4082616,4135979,4189805,4244096,4298854,4354081,4409779,4465950,4522596,4579719,4637321,4695404,4753970,4813021,4872559,4932586,4993104,5054115,5115621,5177624 mov $2,2 lpb $0,1 add $2,$0 sub $0,1 add $1,$2 lpe add $1,1
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/drive/file_system/copy_operation.h" #include <string> #include "base/file_util.h" #include "base/task_runner_util.h" #include "chrome/browser/chromeos/drive/drive.pb.h" #include "chrome/browser/chromeos/drive/file_cache.h" #include "chrome/browser/chromeos/drive/file_system/create_file_operation.h" #include "chrome/browser/chromeos/drive/file_system/operation_observer.h" #include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/chromeos/drive/job_scheduler.h" #include "chrome/browser/chromeos/drive/resource_entry_conversion.h" #include "chrome/browser/chromeos/drive/resource_metadata.h" #include "chrome/browser/drive/drive_api_util.h" #include "content/public/browser/browser_thread.h" #include "google_apis/drive/drive_api_parser.h" using content::BrowserThread; namespace drive { namespace file_system { struct CopyOperation::CopyParams { base::FilePath src_file_path; base::FilePath dest_file_path; bool preserve_last_modified; FileOperationCallback callback; ResourceEntry src_entry; ResourceEntry parent_entry; }; // Enum for categorizing where a gdoc represented by a JSON file exists. enum JsonGdocLocationType { NOT_IN_METADATA, IS_ORPHAN, HAS_PARENT, }; struct CopyOperation::TransferJsonGdocParams { TransferJsonGdocParams(const FileOperationCallback& callback, const std::string& resource_id, const ResourceEntry& parent_entry, const std::string& new_title) : callback(callback), resource_id(resource_id), parent_resource_id(parent_entry.resource_id()), parent_local_id(parent_entry.local_id()), new_title(new_title), location_type(NOT_IN_METADATA) { } // Parameters supplied or calculated from operation arguments. const FileOperationCallback callback; const std::string resource_id; const std::string parent_resource_id; const std::string parent_local_id; const std::string new_title; // Values computed during operation. JsonGdocLocationType location_type; // types where the gdoc file is located. std::string local_id; // the local_id of the file (if exists in metadata.) base::FilePath changed_path; }; namespace { FileError TryToCopyLocally(internal::ResourceMetadata* metadata, internal::FileCache* cache, CopyOperation::CopyParams* params, std::vector<std::string>* updated_local_ids, bool* directory_changed, bool* should_copy_on_server) { FileError error = metadata->GetResourceEntryByPath(params->src_file_path, &params->src_entry); if (error != FILE_ERROR_OK) return error; error = metadata->GetResourceEntryByPath(params->dest_file_path.DirName(), &params->parent_entry); if (error != FILE_ERROR_OK) return error; if (!params->parent_entry.file_info().is_directory()) return FILE_ERROR_NOT_A_DIRECTORY; // Drive File System doesn't support recursive copy. if (params->src_entry.file_info().is_directory()) return FILE_ERROR_NOT_A_FILE; // Check destination. ResourceEntry dest_entry; error = metadata->GetResourceEntryByPath(params->dest_file_path, &dest_entry); switch (error) { case FILE_ERROR_OK: // File API spec says it is an error to try to "copy a file to a path // occupied by a directory". if (dest_entry.file_info().is_directory()) return FILE_ERROR_INVALID_OPERATION; // Move the existing entry to the trash. dest_entry.set_parent_local_id(util::kDriveTrashDirLocalId); error = metadata->RefreshEntry(dest_entry); if (error != FILE_ERROR_OK) return error; updated_local_ids->push_back(dest_entry.local_id()); *directory_changed = true; break; case FILE_ERROR_NOT_FOUND: break; default: return error; } // If the cache file is not present and the entry exists on the server, // server side copy should be used. if (!params->src_entry.file_specific_info().cache_state().is_present() && !params->src_entry.resource_id().empty()) { *should_copy_on_server = true; return FILE_ERROR_OK; } // Copy locally. ResourceEntry entry; const int64 now = base::Time::Now().ToInternalValue(); entry.set_title(params->dest_file_path.BaseName().AsUTF8Unsafe()); entry.set_parent_local_id(params->parent_entry.local_id()); entry.mutable_file_specific_info()->set_content_mime_type( params->src_entry.file_specific_info().content_mime_type()); entry.set_metadata_edit_state(ResourceEntry::DIRTY); entry.set_modification_date(base::Time::Now().ToInternalValue()); entry.mutable_file_info()->set_last_modified( params->preserve_last_modified ? params->src_entry.file_info().last_modified() : now); entry.mutable_file_info()->set_last_accessed(now); std::string local_id; error = metadata->AddEntry(entry, &local_id); if (error != FILE_ERROR_OK) return error; updated_local_ids->push_back(local_id); *directory_changed = true; if (!params->src_entry.file_specific_info().cache_state().is_present()) { DCHECK(params->src_entry.resource_id().empty()); // Locally created empty file may have no cache file. return FILE_ERROR_OK; } base::FilePath cache_file_path; error = cache->GetFile(params->src_entry.local_id(), &cache_file_path); if (error != FILE_ERROR_OK) return error; return cache->Store(local_id, std::string(), cache_file_path, internal::FileCache::FILE_OPERATION_COPY); } // Stores the entry returned from the server and returns its path. FileError UpdateLocalStateForServerSideOperation( internal::ResourceMetadata* metadata, scoped_ptr<google_apis::FileResource> file_resource, base::FilePath* file_path) { DCHECK(file_resource); ResourceEntry entry; std::string parent_resource_id; if (!ConvertFileResourceToResourceEntry(*file_resource, &entry, &parent_resource_id) || parent_resource_id.empty()) return FILE_ERROR_NOT_A_FILE; std::string parent_local_id; FileError error = metadata->GetIdByResourceId(parent_resource_id, &parent_local_id); if (error != FILE_ERROR_OK) return error; entry.set_parent_local_id(parent_local_id); std::string local_id; error = metadata->AddEntry(entry, &local_id); // Depending on timing, the metadata may have inserted via change list // already. So, FILE_ERROR_EXISTS is not an error. if (error == FILE_ERROR_EXISTS) error = metadata->GetIdByResourceId(entry.resource_id(), &local_id); if (error != FILE_ERROR_OK) return error; return metadata->GetFilePath(local_id, file_path); } // Stores the file at |local_file_path| to the cache as a content of entry at // |remote_dest_path|, and marks it dirty. FileError UpdateLocalStateForScheduleTransfer( internal::ResourceMetadata* metadata, internal::FileCache* cache, const base::FilePath& local_src_path, const base::FilePath& remote_dest_path, std::string* local_id) { FileError error = metadata->GetIdByPath(remote_dest_path, local_id); if (error != FILE_ERROR_OK) return error; ResourceEntry entry; error = metadata->GetResourceEntryById(*local_id, &entry); if (error != FILE_ERROR_OK) return error; return cache->Store(*local_id, std::string(), local_src_path, internal::FileCache::FILE_OPERATION_COPY); } // Gets the file size of the |local_path|, and the ResourceEntry for the parent // of |remote_path| to prepare the necessary information for transfer. FileError PrepareTransferFileFromLocalToRemote( internal::ResourceMetadata* metadata, const base::FilePath& local_src_path, const base::FilePath& remote_dest_path, std::string* gdoc_resource_id, ResourceEntry* parent_entry) { FileError error = metadata->GetResourceEntryByPath( remote_dest_path.DirName(), parent_entry); if (error != FILE_ERROR_OK) return error; // The destination's parent must be a directory. if (!parent_entry->file_info().is_directory()) return FILE_ERROR_NOT_A_DIRECTORY; // Try to parse GDoc File and extract the resource id, if necessary. // Failing isn't problem. It'd be handled as a regular file, then. if (util::HasGDocFileExtension(local_src_path)) *gdoc_resource_id = util::ReadResourceIdFromGDocFile(local_src_path); return FILE_ERROR_OK; } // Performs local work before server-side work for transferring JSON-represented // gdoc files. FileError LocalWorkForTransferJsonGdocFile( internal::ResourceMetadata* metadata, CopyOperation::TransferJsonGdocParams* params) { std::string local_id; FileError error = metadata->GetIdByResourceId(params->resource_id, &local_id); if (error != FILE_ERROR_OK) { params->location_type = NOT_IN_METADATA; return error == FILE_ERROR_NOT_FOUND ? FILE_ERROR_OK : error; } ResourceEntry entry; error = metadata->GetResourceEntryById(local_id, &entry); if (error != FILE_ERROR_OK) return error; params->local_id = entry.local_id(); if (entry.parent_local_id() == util::kDriveOtherDirLocalId) { params->location_type = IS_ORPHAN; entry.set_title(params->new_title); entry.set_parent_local_id(params->parent_local_id); entry.set_metadata_edit_state(ResourceEntry::DIRTY); entry.set_modification_date(base::Time::Now().ToInternalValue()); error = metadata->RefreshEntry(entry); if (error != FILE_ERROR_OK) return error; return metadata->GetFilePath(local_id, &params->changed_path); } params->location_type = HAS_PARENT; return FILE_ERROR_OK; } } // namespace CopyOperation::CopyOperation(base::SequencedTaskRunner* blocking_task_runner, OperationObserver* observer, JobScheduler* scheduler, internal::ResourceMetadata* metadata, internal::FileCache* cache, const ResourceIdCanonicalizer& id_canonicalizer) : blocking_task_runner_(blocking_task_runner), observer_(observer), scheduler_(scheduler), metadata_(metadata), cache_(cache), id_canonicalizer_(id_canonicalizer), create_file_operation_(new CreateFileOperation(blocking_task_runner, observer, metadata)), weak_ptr_factory_(this) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); } CopyOperation::~CopyOperation() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); } void CopyOperation::Copy(const base::FilePath& src_file_path, const base::FilePath& dest_file_path, bool preserve_last_modified, const FileOperationCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); CopyParams* params = new CopyParams; params->src_file_path = src_file_path; params->dest_file_path = dest_file_path; params->preserve_last_modified = preserve_last_modified; params->callback = callback; std::vector<std::string>* updated_local_ids = new std::vector<std::string>; bool* directory_changed = new bool(false); bool* should_copy_on_server = new bool(false); base::PostTaskAndReplyWithResult( blocking_task_runner_.get(), FROM_HERE, base::Bind(&TryToCopyLocally, metadata_, cache_, params, updated_local_ids, directory_changed, should_copy_on_server), base::Bind(&CopyOperation::CopyAfterTryToCopyLocally, weak_ptr_factory_.GetWeakPtr(), base::Owned(params), base::Owned(updated_local_ids), base::Owned(directory_changed), base::Owned(should_copy_on_server))); } void CopyOperation::CopyAfterTryToCopyLocally( const CopyParams* params, const std::vector<std::string>* updated_local_ids, const bool* directory_changed, const bool* should_copy_on_server, FileError error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!params->callback.is_null()); for (size_t i = 0; i < updated_local_ids->size(); ++i) observer_->OnEntryUpdatedByOperation((*updated_local_ids)[i]); if (*directory_changed) observer_->OnDirectoryChangedByOperation(params->dest_file_path.DirName()); if (error != FILE_ERROR_OK || !*should_copy_on_server) { params->callback.Run(error); return; } base::FilePath new_title = params->dest_file_path.BaseName(); if (params->src_entry.file_specific_info().is_hosted_document()) { // Drop the document extension, which should not be in the title. // TODO(yoshiki): Remove this code with crbug.com/223304. new_title = new_title.RemoveExtension(); } base::Time last_modified = params->preserve_last_modified ? base::Time::FromInternalValue( params->src_entry.file_info().last_modified()) : base::Time(); CopyResourceOnServer( params->src_entry.resource_id(), params->parent_entry.resource_id(), new_title.AsUTF8Unsafe(), last_modified, params->callback); } void CopyOperation::TransferFileFromLocalToRemote( const base::FilePath& local_src_path, const base::FilePath& remote_dest_path, const FileOperationCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); std::string* gdoc_resource_id = new std::string; ResourceEntry* parent_entry = new ResourceEntry; base::PostTaskAndReplyWithResult( blocking_task_runner_.get(), FROM_HERE, base::Bind( &PrepareTransferFileFromLocalToRemote, metadata_, local_src_path, remote_dest_path, gdoc_resource_id, parent_entry), base::Bind( &CopyOperation::TransferFileFromLocalToRemoteAfterPrepare, weak_ptr_factory_.GetWeakPtr(), local_src_path, remote_dest_path, callback, base::Owned(gdoc_resource_id), base::Owned(parent_entry))); } void CopyOperation::TransferFileFromLocalToRemoteAfterPrepare( const base::FilePath& local_src_path, const base::FilePath& remote_dest_path, const FileOperationCallback& callback, std::string* gdoc_resource_id, ResourceEntry* parent_entry, FileError error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); if (error != FILE_ERROR_OK) { callback.Run(error); return; } // For regular files, schedule the transfer. if (gdoc_resource_id->empty()) { ScheduleTransferRegularFile(local_src_path, remote_dest_path, callback); return; } // GDoc file may contain a resource ID in the old format. const std::string canonicalized_resource_id = id_canonicalizer_.Run(*gdoc_resource_id); // Drop the document extension, which should not be in the title. // TODO(yoshiki): Remove this code with crbug.com/223304. const std::string new_title = remote_dest_path.BaseName().RemoveExtension().AsUTF8Unsafe(); // This is uploading a JSON file representing a hosted document. TransferJsonGdocParams* params = new TransferJsonGdocParams( callback, canonicalized_resource_id, *parent_entry, new_title); base::PostTaskAndReplyWithResult( blocking_task_runner_.get(), FROM_HERE, base::Bind(&LocalWorkForTransferJsonGdocFile, metadata_, params), base::Bind(&CopyOperation::TransferJsonGdocFileAfterLocalWork, weak_ptr_factory_.GetWeakPtr(), base::Owned(params))); } void CopyOperation::TransferJsonGdocFileAfterLocalWork( TransferJsonGdocParams* params, FileError error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (error != FILE_ERROR_OK) { params->callback.Run(error); return; } switch (params->location_type) { // When |resource_id| is found in the local metadata and it has a specific // parent folder, we assume the user's intention is to copy the document and // thus perform the server-side copy operation. case HAS_PARENT: CopyResourceOnServer(params->resource_id, params->parent_resource_id, params->new_title, base::Time(), params->callback); break; // When |resource_id| has no parent, we just set the new destination folder // as the parent, for sharing the document between the original source. // This reparenting is already done in LocalWorkForTransferJsonGdocFile(). case IS_ORPHAN: DCHECK(!params->changed_path.empty()); observer_->OnEntryUpdatedByOperation(params->local_id); observer_->OnDirectoryChangedByOperation(params->changed_path.DirName()); params->callback.Run(error); break; // When the |resource_id| is not in the local metadata, assume it to be a // document just now shared on the server but not synced locally. // Same as the IS_ORPHAN case, we want to deal the case by setting parent, // but this time we need to resort to server side operation. case NOT_IN_METADATA: scheduler_->UpdateResource( params->resource_id, params->parent_resource_id, params->new_title, base::Time(), base::Time(), ClientContext(USER_INITIATED), base::Bind(&CopyOperation::UpdateAfterServerSideOperation, weak_ptr_factory_.GetWeakPtr(), params->callback)); break; } } void CopyOperation::CopyResourceOnServer( const std::string& resource_id, const std::string& parent_resource_id, const std::string& new_title, const base::Time& last_modified, const FileOperationCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); scheduler_->CopyResource( resource_id, parent_resource_id, new_title, last_modified, base::Bind(&CopyOperation::UpdateAfterServerSideOperation, weak_ptr_factory_.GetWeakPtr(), callback)); } void CopyOperation::UpdateAfterServerSideOperation( const FileOperationCallback& callback, google_apis::GDataErrorCode status, scoped_ptr<google_apis::FileResource> entry) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); FileError error = GDataToFileError(status); if (error != FILE_ERROR_OK) { callback.Run(error); return; } // The copy on the server side is completed successfully. Update the local // metadata. base::FilePath* file_path = new base::FilePath; base::PostTaskAndReplyWithResult( blocking_task_runner_.get(), FROM_HERE, base::Bind(&UpdateLocalStateForServerSideOperation, metadata_, base::Passed(&entry), file_path), base::Bind(&CopyOperation::UpdateAfterLocalStateUpdate, weak_ptr_factory_.GetWeakPtr(), callback, base::Owned(file_path))); } void CopyOperation::UpdateAfterLocalStateUpdate( const FileOperationCallback& callback, base::FilePath* file_path, FileError error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); if (error == FILE_ERROR_OK) observer_->OnDirectoryChangedByOperation(file_path->DirName()); callback.Run(error); } void CopyOperation::ScheduleTransferRegularFile( const base::FilePath& local_src_path, const base::FilePath& remote_dest_path, const FileOperationCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); create_file_operation_->CreateFile( remote_dest_path, false, // Not exclusive (OK even if a file already exists). std::string(), // no specific mime type; CreateFile should guess it. base::Bind(&CopyOperation::ScheduleTransferRegularFileAfterCreate, weak_ptr_factory_.GetWeakPtr(), local_src_path, remote_dest_path, callback)); } void CopyOperation::ScheduleTransferRegularFileAfterCreate( const base::FilePath& local_src_path, const base::FilePath& remote_dest_path, const FileOperationCallback& callback, FileError error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); if (error != FILE_ERROR_OK) { callback.Run(error); return; } std::string* local_id = new std::string; base::PostTaskAndReplyWithResult( blocking_task_runner_.get(), FROM_HERE, base::Bind( &UpdateLocalStateForScheduleTransfer, metadata_, cache_, local_src_path, remote_dest_path, local_id), base::Bind( &CopyOperation::ScheduleTransferRegularFileAfterUpdateLocalState, weak_ptr_factory_.GetWeakPtr(), callback, remote_dest_path, base::Owned(local_id))); } void CopyOperation::ScheduleTransferRegularFileAfterUpdateLocalState( const FileOperationCallback& callback, const base::FilePath& remote_dest_path, std::string* local_id, FileError error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); if (error == FILE_ERROR_OK) { observer_->OnDirectoryChangedByOperation(remote_dest_path.DirName()); observer_->OnEntryUpdatedByOperation(*local_id); } callback.Run(error); } } // namespace file_system } // namespace drive
; A108340: A083952 read mod 2. ; 1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 mov $1,$0 gcd $1,2 mov $2,$0 add $2,$0 lpb $2 gcd $1,$2 div $2,5 lpe sub $1,1
;-------------------------------------------------------------------------- ; modsigned.s ; ; Copyright (C) 2009, Philipp Klaus Krause ; ; This library is free software; you can redistribute it and/or modify it ; under the terms of the GNU General Public License as published by the ; Free Software Foundation; either version 2.1, or (at your option) any ; later version. ; ; This library is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this library; see the file COPYING. If not, write to the ; Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, ; MA 02110-1301, USA. ; ; As a special exception, if you link this library with other files, ; some of which are compiled with SDCC, to produce an executable, ; this library does not by itself cause the resulting executable to ; be covered by the GNU General Public License. This exception does ; not however invalidate any other reasons why the executable file ; might be covered by the GNU General Public License. ;-------------------------------------------------------------------------- SECTION code_l_sdcc PUBLIC __modschar_rrx_s PUBLIC __modschar_rrx_hds EXTERN __div8 EXTERN __get_remainder PUBLIC __modsint_rrx_s PUBLIC __modsint_rrx_hds EXTERN __div16 __modschar_rrx_s: ld hl,#2+1 add hl,sp ld e,(hl) dec hl ld l,(hl) ;; Fall through __modschar_rrx_hds: call __div8 jp __get_remainder __modsint_rrx_s: pop af pop hl pop de push de push hl push af ;; Fall through __modsint_rrx_hds: call __div16 jp __get_remainder
; ; Copyright (c) 2010 The WebM project authors. All Rights Reserved. ; ; Use of this source code is governed by a BSD-style license ; that can be found in the LICENSE file in the root of the source ; tree. An additional intellectual property rights grant can be found ; in the file PATENTS. All contributing project authors may ; be found in the AUTHORS file in the root of the source tree. ; %include "vpx_ports/x86_abi_support.asm" %macro VERTx4 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movq xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm0, xmm4, 0b ;k0_k1 pshuflw xmm1, xmm4, 01010101b ;k2_k3 pshuflw xmm2, xmm4, 10101010b ;k4_k5 pshuflw xmm3, xmm4, 11111111b ;k6_k7 punpcklqdq xmm0, xmm0 punpcklqdq xmm1, xmm1 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 movdqa k0k1, xmm0 movdqa k2k3, xmm1 pshufd xmm5, xmm5, 0 movdqa k4k5, xmm2 movdqa k6k7, xmm3 movdqa krd, xmm5 movsxd rdx, DWORD PTR arg(1) ;pixels_per_line %if ABI_IS_32BIT=0 movsxd r8, DWORD PTR arg(3) ;out_pitch %endif mov rax, rsi movsxd rcx, DWORD PTR arg(4) ;output_height add rax, rdx lea rbx, [rdx + rdx*4] add rbx, rdx ;pitch * 6 .loop: movd xmm0, [rsi] ;A movd xmm1, [rsi + rdx] ;B movd xmm2, [rsi + rdx * 2] ;C movd xmm3, [rax + rdx * 2] ;D movd xmm4, [rsi + rdx * 4] ;E movd xmm5, [rax + rdx * 4] ;F punpcklbw xmm0, xmm1 ;A B punpcklbw xmm2, xmm3 ;C D punpcklbw xmm4, xmm5 ;E F movd xmm6, [rsi + rbx] ;G movd xmm7, [rax + rbx] ;H pmaddubsw xmm0, k0k1 pmaddubsw xmm2, k2k3 punpcklbw xmm6, xmm7 ;G H pmaddubsw xmm4, k4k5 pmaddubsw xmm6, k6k7 movdqa xmm1, xmm2 paddsw xmm0, xmm6 pmaxsw xmm2, xmm4 pminsw xmm4, xmm1 paddsw xmm0, xmm4 paddsw xmm0, xmm2 paddsw xmm0, krd psraw xmm0, 7 packuswb xmm0, xmm0 add rsi, rdx add rax, rdx %if %1 movd xmm1, [rdi] pavgb xmm0, xmm1 %endif movd [rdi], xmm0 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;out_pitch %else add rdi, r8 %endif dec rcx jnz .loop %endm %macro VERTx8 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movq xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm0, xmm4, 0b ;k0_k1 pshuflw xmm1, xmm4, 01010101b ;k2_k3 pshuflw xmm2, xmm4, 10101010b ;k4_k5 pshuflw xmm3, xmm4, 11111111b ;k6_k7 punpcklqdq xmm0, xmm0 punpcklqdq xmm1, xmm1 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 movdqa k0k1, xmm0 movdqa k2k3, xmm1 pshufd xmm5, xmm5, 0 movdqa k4k5, xmm2 movdqa k6k7, xmm3 movdqa krd, xmm5 movsxd rdx, DWORD PTR arg(1) ;pixels_per_line %if ABI_IS_32BIT=0 movsxd r8, DWORD PTR arg(3) ;out_pitch %endif mov rax, rsi movsxd rcx, DWORD PTR arg(4) ;output_height add rax, rdx lea rbx, [rdx + rdx*4] add rbx, rdx ;pitch * 6 .loop: movq xmm0, [rsi] ;A movq xmm1, [rsi + rdx] ;B movq xmm2, [rsi + rdx * 2] ;C movq xmm3, [rax + rdx * 2] ;D movq xmm4, [rsi + rdx * 4] ;E movq xmm5, [rax + rdx * 4] ;F punpcklbw xmm0, xmm1 ;A B punpcklbw xmm2, xmm3 ;C D punpcklbw xmm4, xmm5 ;E F movq xmm6, [rsi + rbx] ;G movq xmm7, [rax + rbx] ;H pmaddubsw xmm0, k0k1 pmaddubsw xmm2, k2k3 punpcklbw xmm6, xmm7 ;G H pmaddubsw xmm4, k4k5 pmaddubsw xmm6, k6k7 paddsw xmm0, xmm6 movdqa xmm1, xmm2 pmaxsw xmm2, xmm4 pminsw xmm4, xmm1 paddsw xmm0, xmm4 paddsw xmm0, xmm2 paddsw xmm0, krd psraw xmm0, 7 packuswb xmm0, xmm0 add rsi, rdx add rax, rdx %if %1 movq xmm1, [rdi] pavgb xmm0, xmm1 %endif movq [rdi], xmm0 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;out_pitch %else add rdi, r8 %endif dec rcx jnz .loop %endm %macro VERTx16 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movq xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm0, xmm4, 0b ;k0_k1 pshuflw xmm1, xmm4, 01010101b ;k2_k3 pshuflw xmm2, xmm4, 10101010b ;k4_k5 pshuflw xmm3, xmm4, 11111111b ;k6_k7 punpcklqdq xmm0, xmm0 punpcklqdq xmm1, xmm1 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 movdqa k0k1, xmm0 movdqa k2k3, xmm1 pshufd xmm5, xmm5, 0 movdqa k4k5, xmm2 movdqa k6k7, xmm3 movdqa krd, xmm5 movsxd rdx, DWORD PTR arg(1) ;pixels_per_line %if ABI_IS_32BIT=0 movsxd r8, DWORD PTR arg(3) ;out_pitch %endif mov rax, rsi movsxd rcx, DWORD PTR arg(4) ;output_height add rax, rdx lea rbx, [rdx + rdx*4] add rbx, rdx ;pitch * 6 .loop: movq xmm0, [rsi] ;A movq xmm1, [rsi + rdx] ;B movq xmm2, [rsi + rdx * 2] ;C movq xmm3, [rax + rdx * 2] ;D movq xmm4, [rsi + rdx * 4] ;E movq xmm5, [rax + rdx * 4] ;F punpcklbw xmm0, xmm1 ;A B punpcklbw xmm2, xmm3 ;C D punpcklbw xmm4, xmm5 ;E F movq xmm6, [rsi + rbx] ;G movq xmm7, [rax + rbx] ;H pmaddubsw xmm0, k0k1 pmaddubsw xmm2, k2k3 punpcklbw xmm6, xmm7 ;G H pmaddubsw xmm4, k4k5 pmaddubsw xmm6, k6k7 paddsw xmm0, xmm6 movdqa xmm1, xmm2 pmaxsw xmm2, xmm4 pminsw xmm4, xmm1 paddsw xmm0, xmm4 paddsw xmm0, xmm2 paddsw xmm0, krd psraw xmm0, 7 packuswb xmm0, xmm0 %if %1 movq xmm1, [rdi] pavgb xmm0, xmm1 %endif movq [rdi], xmm0 movq xmm0, [rsi + 8] ;A movq xmm1, [rsi + rdx + 8] ;B movq xmm2, [rsi + rdx * 2 + 8] ;C movq xmm3, [rax + rdx * 2 + 8] ;D movq xmm4, [rsi + rdx * 4 + 8] ;E movq xmm5, [rax + rdx * 4 + 8] ;F punpcklbw xmm0, xmm1 ;A B punpcklbw xmm2, xmm3 ;C D punpcklbw xmm4, xmm5 ;E F movq xmm6, [rsi + rbx + 8] ;G movq xmm7, [rax + rbx + 8] ;H punpcklbw xmm6, xmm7 ;G H pmaddubsw xmm0, k0k1 pmaddubsw xmm2, k2k3 pmaddubsw xmm4, k4k5 pmaddubsw xmm6, k6k7 paddsw xmm0, xmm6 movdqa xmm1, xmm2 pmaxsw xmm2, xmm4 pminsw xmm4, xmm1 paddsw xmm0, xmm4 paddsw xmm0, xmm2 paddsw xmm0, krd psraw xmm0, 7 packuswb xmm0, xmm0 add rsi, rdx add rax, rdx %if %1 movq xmm1, [rdi+8] pavgb xmm0, xmm1 %endif movq [rdi+8], xmm0 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;out_pitch %else add rdi, r8 %endif dec rcx jnz .loop %endm ;void vp9_filter_block1d8_v8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pitch, ; unsigned char *output_ptr, ; unsigned int out_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d4_v8_ssse3) PRIVATE sym(vp9_filter_block1d4_v8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx4 0 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp9_filter_block1d8_v8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pitch, ; unsigned char *output_ptr, ; unsigned int out_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d8_v8_ssse3) PRIVATE sym(vp9_filter_block1d8_v8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx8 0 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp9_filter_block1d16_v8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pitch, ; unsigned char *output_ptr, ; unsigned int out_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d16_v8_ssse3) PRIVATE sym(vp9_filter_block1d16_v8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx16 0 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ global sym(vp9_filter_block1d4_v8_avg_ssse3) PRIVATE sym(vp9_filter_block1d4_v8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx4 1 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret global sym(vp9_filter_block1d8_v8_avg_ssse3) PRIVATE sym(vp9_filter_block1d8_v8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx8 1 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret global sym(vp9_filter_block1d16_v8_avg_ssse3) PRIVATE sym(vp9_filter_block1d16_v8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx16 1 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %macro HORIZx4_ROW 2 movdqa %2, %1 pshufb %1, [GLOBAL(shuf_t0t1)] pshufb %2, [GLOBAL(shuf_t2t3)] pmaddubsw %1, k0k1k4k5 pmaddubsw %2, k2k3k6k7 movdqa xmm4, %1 movdqa xmm5, %2 psrldq %1, 8 psrldq %2, 8 movdqa xmm6, xmm5 paddsw xmm4, %2 pmaxsw xmm5, %1 pminsw %1, xmm6 paddsw %1, xmm4 paddsw %1, xmm5 paddsw %1, krd psraw %1, 7 packuswb %1, %1 %endm %macro HORIZx4 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movq xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm6, xmm4, 0b ;k0_k1 pshufhw xmm6, xmm6, 10101010b ;k0_k1_k4_k5 pshuflw xmm7, xmm4, 01010101b ;k2_k3 pshufhw xmm7, xmm7, 11111111b ;k2_k3_k6_k7 pshufd xmm5, xmm5, 0 ;rounding movdqa k0k1k4k5, xmm6 movdqa k2k3k6k7, xmm7 movdqa krd, xmm5 movsxd rax, dword ptr arg(1) ;src_pixels_per_line movsxd rdx, dword ptr arg(3) ;output_pitch movsxd rcx, dword ptr arg(4) ;output_height shr rcx, 1 .loop: ;Do two rows once movq xmm0, [rsi - 3] ;load src movq xmm1, [rsi + 5] movq xmm2, [rsi + rax - 3] movq xmm3, [rsi + rax + 5] punpcklqdq xmm0, xmm1 punpcklqdq xmm2, xmm3 HORIZx4_ROW xmm0, xmm1 HORIZx4_ROW xmm2, xmm3 %if %1 movd xmm1, [rdi] pavgb xmm0, xmm1 movd xmm3, [rdi + rdx] pavgb xmm2, xmm3 %endif movd [rdi], xmm0 movd [rdi +rdx], xmm2 lea rsi, [rsi + rax] prefetcht0 [rsi + 4 * rax - 3] lea rsi, [rsi + rax] lea rdi, [rdi + 2 * rdx] prefetcht0 [rsi + 2 * rax - 3] dec rcx jnz .loop ; Do last row if output_height is odd movsxd rcx, dword ptr arg(4) ;output_height and rcx, 1 je .done movq xmm0, [rsi - 3] ; load src movq xmm1, [rsi + 5] punpcklqdq xmm0, xmm1 HORIZx4_ROW xmm0, xmm1 %if %1 movd xmm1, [rdi] pavgb xmm0, xmm1 %endif movd [rdi], xmm0 .done %endm %macro HORIZx8_ROW 4 movdqa %2, %1 movdqa %3, %1 movdqa %4, %1 pshufb %1, [GLOBAL(shuf_t0t1)] pshufb %2, [GLOBAL(shuf_t2t3)] pshufb %3, [GLOBAL(shuf_t4t5)] pshufb %4, [GLOBAL(shuf_t6t7)] pmaddubsw %1, k0k1 pmaddubsw %2, k2k3 pmaddubsw %3, k4k5 pmaddubsw %4, k6k7 paddsw %1, %4 movdqa %4, %2 pmaxsw %2, %3 pminsw %3, %4 paddsw %1, %3 paddsw %1, %2 paddsw %1, krd psraw %1, 7 packuswb %1, %1 %endm %macro HORIZx8 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movq xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm0, xmm4, 0b ;k0_k1 pshuflw xmm1, xmm4, 01010101b ;k2_k3 pshuflw xmm2, xmm4, 10101010b ;k4_k5 pshuflw xmm3, xmm4, 11111111b ;k6_k7 punpcklqdq xmm0, xmm0 punpcklqdq xmm1, xmm1 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 movdqa k0k1, xmm0 movdqa k2k3, xmm1 pshufd xmm5, xmm5, 0 movdqa k4k5, xmm2 movdqa k6k7, xmm3 movdqa krd, xmm5 movsxd rax, dword ptr arg(1) ;src_pixels_per_line movsxd rdx, dword ptr arg(3) ;output_pitch movsxd rcx, dword ptr arg(4) ;output_height shr rcx, 1 .loop: movq xmm0, [rsi - 3] ;load src movq xmm3, [rsi + 5] movq xmm4, [rsi + rax - 3] movq xmm7, [rsi + rax + 5] punpcklqdq xmm0, xmm3 punpcklqdq xmm4, xmm7 HORIZx8_ROW xmm0, xmm1, xmm2, xmm3 HORIZx8_ROW xmm4, xmm5, xmm6, xmm7 %if %1 movq xmm1, [rdi] movq xmm2, [rdi + rdx] pavgb xmm0, xmm1 pavgb xmm4, xmm2 %endif movq [rdi], xmm0 movq [rdi + rdx], xmm4 lea rsi, [rsi + rax] prefetcht0 [rsi + 4 * rax - 3] lea rsi, [rsi + rax] lea rdi, [rdi + 2 * rdx] prefetcht0 [rsi + 2 * rax - 3] dec rcx jnz .loop ;Do last row if output_height is odd movsxd rcx, dword ptr arg(4) ;output_height and rcx, 1 je .done movq xmm0, [rsi - 3] movq xmm3, [rsi + 5] punpcklqdq xmm0, xmm3 HORIZx8_ROW xmm0, xmm1, xmm2, xmm3 %if %1 movq xmm1, [rdi] pavgb xmm0, xmm1 %endif movq [rdi], xmm0 .done %endm %macro HORIZx16 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movq xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm0, xmm4, 0b ;k0_k1 pshuflw xmm1, xmm4, 01010101b ;k2_k3 pshuflw xmm2, xmm4, 10101010b ;k4_k5 pshuflw xmm3, xmm4, 11111111b ;k6_k7 punpcklqdq xmm0, xmm0 punpcklqdq xmm1, xmm1 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 movdqa k0k1, xmm0 movdqa k2k3, xmm1 pshufd xmm5, xmm5, 0 movdqa k4k5, xmm2 movdqa k6k7, xmm3 movdqa krd, xmm5 movsxd rax, dword ptr arg(1) ;src_pixels_per_line movsxd rdx, dword ptr arg(3) ;output_pitch movsxd rcx, dword ptr arg(4) ;output_height .loop: prefetcht0 [rsi + 2 * rax -3] movq xmm0, [rsi - 3] ;load src data movq xmm4, [rsi + 5] movq xmm6, [rsi + 13] punpcklqdq xmm0, xmm4 punpcklqdq xmm4, xmm6 movdqa xmm7, xmm0 punpcklbw xmm7, xmm7 punpckhbw xmm0, xmm0 movdqa xmm1, xmm0 movdqa xmm2, xmm0 movdqa xmm3, xmm0 palignr xmm0, xmm7, 1 palignr xmm1, xmm7, 5 pmaddubsw xmm0, k0k1 palignr xmm2, xmm7, 9 pmaddubsw xmm1, k2k3 palignr xmm3, xmm7, 13 pmaddubsw xmm2, k4k5 pmaddubsw xmm3, k6k7 paddsw xmm0, xmm3 movdqa xmm3, xmm4 punpcklbw xmm3, xmm3 punpckhbw xmm4, xmm4 movdqa xmm5, xmm4 movdqa xmm6, xmm4 movdqa xmm7, xmm4 palignr xmm4, xmm3, 1 palignr xmm5, xmm3, 5 palignr xmm6, xmm3, 9 palignr xmm7, xmm3, 13 movdqa xmm3, xmm1 pmaddubsw xmm4, k0k1 pmaxsw xmm1, xmm2 pmaddubsw xmm5, k2k3 pminsw xmm2, xmm3 pmaddubsw xmm6, k4k5 paddsw xmm0, xmm2 pmaddubsw xmm7, k6k7 paddsw xmm0, xmm1 paddsw xmm4, xmm7 movdqa xmm7, xmm5 pmaxsw xmm5, xmm6 pminsw xmm6, xmm7 paddsw xmm4, xmm6 paddsw xmm4, xmm5 paddsw xmm0, krd paddsw xmm4, krd psraw xmm0, 7 psraw xmm4, 7 packuswb xmm0, xmm0 packuswb xmm4, xmm4 punpcklqdq xmm0, xmm4 %if %1 movdqa xmm1, [rdi] pavgb xmm0, xmm1 %endif lea rsi, [rsi + rax] movdqa [rdi], xmm0 lea rdi, [rdi + rdx] dec rcx jnz .loop %endm ;void vp9_filter_block1d4_h8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pixels_per_line, ; unsigned char *output_ptr, ; unsigned int output_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d4_h8_ssse3) PRIVATE sym(vp9_filter_block1d4_h8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16 * 3 %define k0k1k4k5 [rsp + 16 * 0] %define k2k3k6k7 [rsp + 16 * 1] %define krd [rsp + 16 * 2] HORIZx4 0 add rsp, 16 * 3 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp9_filter_block1d8_h8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pixels_per_line, ; unsigned char *output_ptr, ; unsigned int output_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d8_h8_ssse3) PRIVATE sym(vp9_filter_block1d8_h8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] HORIZx8 0 add rsp, 16*5 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp9_filter_block1d16_h8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pixels_per_line, ; unsigned char *output_ptr, ; unsigned int output_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d16_h8_ssse3) PRIVATE sym(vp9_filter_block1d16_h8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] HORIZx16 0 add rsp, 16*5 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret global sym(vp9_filter_block1d4_h8_avg_ssse3) PRIVATE sym(vp9_filter_block1d4_h8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16 * 3 %define k0k1k4k5 [rsp + 16 * 0] %define k2k3k6k7 [rsp + 16 * 1] %define krd [rsp + 16 * 2] HORIZx4 1 add rsp, 16 * 3 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret global sym(vp9_filter_block1d8_h8_avg_ssse3) PRIVATE sym(vp9_filter_block1d8_h8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] HORIZx8 1 add rsp, 16*5 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret global sym(vp9_filter_block1d16_h8_avg_ssse3) PRIVATE sym(vp9_filter_block1d16_h8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] HORIZx16 1 add rsp, 16*5 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret SECTION_RODATA align 16 shuf_t0t1: db 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8 align 16 shuf_t2t3: db 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10 align 16 shuf_t4t5: db 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12 align 16 shuf_t6t7: db 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14
#include<iostream> #include<fstream> using namespace std; int main(){ fstream sf; sf.open("output.txt",ios::app); string name; cout<<"enter name of file you want to append "; cin>>name; ifstream fi; fi.open(name); string line; while (!fi.eof()) { getline(fi,line); sf<<line<<endl; } fi.close(); sf.close(); fi.open("output.txt"); while (!fi.eof()) { getline(fi,line); cout<<line<<endl; } }
; boot12.asm FAT12 bootstrap for real mode image or loader ; Version 1.0, Jul 5, 1999 ; Sample code ; by John S. Fine johnfine@erols.com ; I do not place any restrictions on your use of this source code ; I do not provide any warranty of the correctness of this source code ;_____________________________________________________________________________ ; ; Documentation: ; ; I) BASIC features ; II) Compiling and installing ; III) Detailed features and limits ; IV) Customization ;_____________________________________________________________________________ ; ; I) BASIC features ; ; This boot sector will load and start a real mode image from a file in the ; root directory of a FAT12 formatted floppy or partition. ; ; Inputs: ; DL = drive number ; ; Outputs: ; The boot record is left in memory at 7C00 and the drive number is patched ; into the boot record at 7C24. ; SS = DS = 0 ; BP = 7C00 ;_____________________________________________________________________________ ; ; II) Compiling and installing ; ; To compile, use NASM ; ; nasm boot12.asm -o boot12.bin ; ; Then you must copy the first three bytes of BOOT12.BIN to the first three ; bytes of the volume and copy bytes 0x3E through 0x1FF of BOOT12.BIN to ; bytes 0x3E through 0x1FF of the volume. Bytes 0x3 through 0x3D of the ; volume should be set by a FAT12 format program and should not be modified ; when copying boot12.bin to the volume. ; ; If you use my PARTCOPY program to install BOOT12.BIN on A:, the ; commands are: ; ; partcopy boot12.bin 0 3 -f0 ; partcopy boot12.bin 3e 1c2 -f0 3e ; ; PARTCOPY can also install to a partition on a hard drive. Please read ; partcopy documentation and use it carefully. Careless use could overwrite ; important parts of your hard drive. ; ; You can find PARTCOPY and links to NASM on my web page at ; http://www.erols.com/johnfine/ ;_____________________________________________________________________________ ; ; III) Detailed features and limits ; ; Most of the limits are stable characteristics of the volume. If you are ; using boot12 in a personal project, you should check the limits before ; installing boot12. If you are using boot12 in a project for general ; distribution, you should include an installation program which checks the ; limits automatically. ; ; CPU: Supports any 8088+ CPU. ; ; Volume format: Supports only FAT12. ; ; Sector size: Supports only 512 bytes per sector. ; ; Drive/Partition: Supports whole drive or any partition of any drive number ; supported by INT 13h. ; ; Diskette parameter table: This code does not patch the diskette parameter ; table. If you boot this code from a diskette that has more sectors per ; track than the default initialized by the BIOS then the failure to patch ; that table may be a problem. Because this code splits at track boundaries ; a diskette with fewer sectors per track should not be a problem. ; ; File position: The file name may be anywhere in the root directory and the ; file may be any collection of clusters on the volume. There are no ; contiguity requirements. (But see track limit). ; ; Track boundaries: Transfers are split on track boundaries. Many BIOS's ; require that the caller split floppy transfers on track boundaries. ; ; 64Kb boundaries: Transfers are split on 64Kb boundaries. Many BIOS's ; require that the caller split floppy transfers on track boundaries. ; ; Cluster boundaries: Transfers are merged across cluster boundaries whenever ; possible. On some systems, this significantly reduces load time. ; ; Cluster 2 limit: Cluster 2 must start before sector 65536 of the volume. ; This is very likely because only the reserved sectors (usually 1) and ; the FAT's (two of up to 12 sectors each) and the root directory (usually ; either 15 or 32 sectors) precede cluster 2. ; ; Track limit: The entire image file must reside before track 32768 of the ; entire volume. This is true on most media up to 1GB in size. If it is a ; problem it is easy to fix (see boot16.asm). I didn't expect many people ; to put FAT12 partitions beyond the first GB of a large hard drive. ; ; Memory boundaries: The FAT, Root directory, and Image must all be loaded ; starting at addresses that are multiples of 512 bytes (32 paragraphs). ; ; Memory use: The FAT and Root directory must each fit entirely in the ; first 64Kb of RAM. They may overlap. ; ; Root directory size: As released, it supports up to 928 entries in the ; root directory. If ROOT_SEG were changed to 0x7E0 it would support up ; to 1040. Most FAT12 volumes have either 240 or 512 root directory ; entries. ;_____________________________________________________________________________ ; ; IV) Customization ; ; The memory usage can be customized by changing the _SEG variables (see ; directly below). ; ; The file name to be loaded and the message displayed in case of error ; may be customized (see end of this file). ; ; The ouput values may be customized. For example, many loaders expect the ; bootsector to leave the drive number in DL. You could add "mov dl,[drive]" ; at the label "eof:". ; ; Some limits (like maximum track) may be removed. See boot16.asm for ; comparison. ; ; Change whatever else you like. The above are just likely possibilities. ;_____________________________________________________________________________ ; Change the _SEG values to customize memory use during the boot. ; When planning memory use, remember: ; ; *) Each of ROOT_SEG, FAT_SEG, and IMAGE_SEG must be divisible by 0x20 ; ; *) None of ROOT, FAT or IMAGE should overlap the boot code itself, or ; its stack. That means: avoid paragraphs 0x7B0 to 0x7DF. ; ; *) The FAT area must not overlap the IMAGE area. Either may overlap ; the ROOT area; But, if they do then the root will not remain in ; memory for possible reuse by the next stage. ; ; *) The FAT area and the root area must each fit within the first 64Kb ; excluding BIOS area (paragraphs 0x60 to 0xFFF). ; ; *) A FAT12 FAT can be up to 6Kb (0x180 paragraphs). ; ; *) A FAT12 root directory is typically either 0x1E0 or 0x400 paragraphs ; long, but larger sizes are possible. ; ; *) The code will be two bytes shorter when FAT_SEG is 0x800 than when it ; is another value. (If you reach the point of caring about two bytes). ; %define ROOT_SEG 0x60 %define FAT_SEG 0x800 %define IMAGE_SEG 0x1000 %if ROOT_SEG & 31 %error "ROOT_SEG must be divisible by 0x20" %endif %if ROOT_SEG > 0xC00 %error "Root directory must fit within first 64Kb" %endif %if FAT_SEG & 31 %error "FAT_SEG must be divisible by 0x20" %endif %if FAT_SEG > 0xE80 %error "FAT must fit within first 64Kb" %endif %if IMAGE_SEG & 31 %error "IMAGE_SEG must be divisible by 0x20" %endif ; The following %define directives declare the parts of the FAT12 "DOS BOOT ; RECORD" that are used by this code, based on BP being set to 7C00. ; %define sc_p_clu bp+0Dh ;byte Sectors per cluster %define sc_b4_fat bp+0Eh ;word Sectors (in partition) before FAT %define fats bp+10h ;byte Number of FATs %define dir_ent bp+11h ;word Number of root directory entries %define sc_p_fat bp+16h ;word Sectors per FAT %define sc_p_trk bp+18h ;word Sectors per track %define heads bp+1Ah ;word Number of heads %define sc_b4_prt bp+1Ch ;dword Sectors before partition %define drive bp+24h ;byte Drive number org 0x7C00 entry: jmp short begin nop OEMLabel db "UVLIGHT " ; Disk label BytesPerSector dw 512 ; Bytes per sector SectorsPerCluster db 1 ; Sectors per cluster ReservedForBoot dw 1 ; Reserved sectors for boot record NumberOfFats db 2 ; Number of copies of the FAT RootDirEntries dw 224 ; Number of entries in root dir ; (224 * 32 = 7168 = 14 sectors to read) LogicalSectors dw 2880 ; Number of logical sectors MediumByte db 0F0h ; Medium descriptor byte SectorsPerFat dw 9 ; Sectors per FAT SectorsPerTrack dw 18 ; Sectors per track (36/cylinder) Sides dw 2 ; Number of sides/heads HiddenSectors dd 0 ; Number of hidden sectors LargeSectors dd 0 ; Number of LBA sectors DriveNo dw 0 ; Drive No: 0 Signature db 41 ; Drive signature: 41 for floppy VolumeID dd 00000000h ; Volume ID: any number VolumeLabel db "BLACKLIGHT "; Volume Label: any 11 chars FileSystem db "FAT12 " ; File system type: don't change! begin: xor ax, ax mov ds, ax mov ss, ax mov sp, 0x7C00 mov bp, sp mov [drive], dl ;Drive number mov al, [fats] ;Number of FATs mul word [sc_p_fat] ; * Sectors per FAT add ax, [sc_b4_fat] ; + Sectors before FAT ;AX = Sector of Root directory mov si, [dir_ent] ;Max root directory entries mov cl, 4 dec si shr si, cl inc si ;SI = Length of root in sectors mov di, ROOT_SEG/32 ;Buffer (paragraph / 32) call read_16 ;Read root directory push ax ;Sector of cluster two %define sc_clu2 bp-2 ;Later access to the word just pushed is via bp mov dx, [dir_ent] ;Number of directory entries push ds pop es mov di, ROOT_SEG*16 search: dec dx ;Any more directory entries? js error ;No mov si, filename ;Name we are searching for mov cx, 11 ;11 characters long lea ax, [di+0x20] ;Precompute next entry address push ax repe cmpsb ;Compare pop di jnz search ;Repeat until match push word [di-6] ;Starting cluster number mov ax, [sc_b4_fat] ;Sector number of FAT mov si, [sc_p_fat] ;Length of FAT mov di, FAT_SEG/32 ;Buffer (paragraph / 32) call read_16 ;Read FAT next: pop bx ;Cluster number mov si, bx ;First cluster in this sequence mov ax, bx ;Last cluster in this sequence .0: cmp bx, 0xFF8 ;End of file? jae .2 ; Yes inc ax ;Last cluster plus one in sequence ;Look in FAT for next cluster mov di, bx ;Cluster number rcr bx, 1 ;1.5 byte entry per cluster ;bx = 0x8000 + cluster/2 ;c-bit set for odd clusters mov bx, [bx+di+FAT_SEG*16-0x8000] jnc .1 shr bx, 1 shr bx, 1 shr bx, 1 shr bx, 1 .1: and bh, 0xF cmp ax, bx ;Is the next one contiguous? je .0 ;Yes: look further ahead .2: sub ax, si ;How many contiguous in this sequence? jz eof ;None, must be done. push bx ;Save next (eof or discontiguous) cluster mov bl, [sc_p_clu] ;Sectors per cluster mov bh, 0 ; as a word mul bx ;Length of sequence in sectors .3: mov di, IMAGE_SEG/32 ;Destination (paragraph / 32) add [.3+1], ax ;Precompute next destination xchg ax, si ;AX = starting cluster ;SI = length in sectors dec ax dec ax ;Starting cluster minus two mul bx ; * sectors per cluster add ax, [sc_clu2] ; + sector number of cluster two adc dl, dh ;Allow 24-bit result call read_32 ;Read it jmp short next ;Look for more eof: mov dl,[drive] jmp IMAGE_SEG:0 error: mov si, errmsg ;Same message for all detected errors mov ax, 0xE0D ;Start message with CR mov bx, 7 .1: int 10h lodsb test al, al jnz .1 xor ah, ah int 16h ;Wait for a key int 19h ;Try to reboot read_16: xor dx, dx read_32: ; ; Input: ; dx:ax = sector within partition ; si = sector count ; di = destination segment / 32 ; ; The sector number is converted from a partition-relative to a whole-disk ; (LBN) value, and then converted to CHS form, and then the sectors are read ; into (di*32):0. ; ; Output: ; dx:ax updated (sector count added) ; di updated (sector count added) ; si = 0 ; bp, ds preserved ; bx, cx, es modified .1: push dx ;(high) relative sector push ax ;(low) relative sector add ax, [sc_b4_prt] ;Convert to LBN adc dx, [sc_b4_prt+2] mov bx, [sc_p_trk] ;Sectors per track div bx ;AX = track ;DX = sector-1 sub bx, dx ;Sectors remaining, this track cmp bx, si ;More than we want? jbe .2 ;No mov bx, si ;Yes: Transfer just what we want .2: inc dx ;Sector number mov cx, dx ;CL = sector ;CH = 0 cwd ;(This supports up to 32767 tracks div word [heads] ;Track number / Number of heads mov dh, dl ;DH = head xchg ch, al ;CH = (low) cylinder ;AL=0 ror ah, 1 ;rotate (high) cylinder ror ah, 1 add cl, ah ;CL = combine: sector, (high) cylinder sub ax, di and ax, byte 0x7F ;AX = sectors to next 64Kb boundary jz .3 ;On a 64Kb boundary already cmp ax, bx ;More than we want? jbe .4 ;No .3: xchg ax, bx ;Yes: Transfer just what we want .4: push ax ;Save length mov bx, di ;Compute destination seg push cx mov cl, 5 shl bx, cl pop cx mov es, bx xor bx, bx ;ES:BX = address mov dl, [drive] ;DL = Drive number mov ah, 2 ;AH = Read command int 13h ;Do it jc error pop bx ;Length pop ax ;(low) relative sector pop dx ;(high) relative sector add ax, bx ;Update relative sector adc dl, dh add di, bx ;Update destination sub si, bx ;Update count jnz .1 ;Read some more ret errmsg db 10,"Error Executing FAT12 bootsector",13 db 10,"Press any key to reboot",13,10,0 size equ $ - entry %if size+11+2 > 512 %error "code is too large for boot sector" %endif times (512 - size - 11 - 2) db 0 filename db "UVLIGHT KRN" ;11 byte name db 0x55, 0xAA ;2 byte boot signature
#include "larva_creep_spawn.h" #include <SCBW/api.h> //Helper functions definitions namespace { void setUnitPathing(CUnit* unit, u8 unkPathRelated); //0x00401360 bool isUnitPositions2Equal(CUnit* unit); //0x00402160 CUnit* connectAddonCheck(CUnit* unit); //0x004404A0 void function_00463470(CUnit* unit); //0x00463470 void function_004634E0(CUnit* unit); //0x004634E0 void function_00463640(CUnit* unit); //0x00463640 void completeAddon(CUnit* unit, CUnit* addon); //0x00463D50 void function_00464300(CUnit* unit); //0x00464300 void disconnectFromAddOn(CUnit* unit); //0x00464930 void function_00469EC0(CUnit* unit, int x, int y); //0x00469EC0 void function_00469F60(CUnit* unit, int x, int y); //0x00469F60 void function_0046A560(CUnit* unit); //0x0046A560 void function_0046A5A0(CUnit* unit); //0x0046A5A0 u32 function_00473FB0(CUnit* unit, u8 playerId, int x, int y, u16 unitId, u8 unk1, u8 unk2, u8 unk3, u8 unk4 ); //0x00473FB0 void removeOrderFromUnitQueue(CUnit* unit, COrder* order); //0x004742D0 void function_00474760(CUnit* unit, COrder* order, u8 orderId); //0x00474760 void actUnitReturnToIdle(CUnit* unit); //0x00475420 bool function_0047DF90(CUnit* unit); //0x0047DF90 void refreshLayer3And4(); //0x0048D9A0 bool function_0048DDA0(); //0x0048DDA0 void function_0048E310(); //0x0048E310 void placebuildingProc(); //0x0048E6E0 void playBuildingLandSound(CUnit* unit); //0x0048F5A0 void SetUnitMovementSpeed(CUnit* unit, u32 newSpeed); //0x004951C0 void function_00498150(CSprite* sprite, u8 newVerticalOffset); //0x00498150 void function_004997E0(CSprite* sprite); //0x004997E0 void function_004C3B40(CUnit* unit); //0x004C3B40 bool function_004EB9C0(CUnit* unit, int x, int y); //0x004EB9C0 } //unnamed namespace namespace hooks { void orders_BuildingLand(CUnit* unit) { Target unitTarget; unitTarget.unit = unit->orderTarget.unit; //[ebp-04] unitTarget.pt = unit->orderTarget.pt; //[ebp-08] Point16 coords; coords.x = 0; //[ebp-10] coords.y = 0; //[ebp-0e] if(unit->status & UnitStatus::GroundedBuilding) { unit->userActionFlags |= 1; if(unit->mainOrderId != OrderId::Die) { bool bLoopBreak = false; //643B0 while(unit->orderQueueTail != NULL && !bLoopBreak) { bLoopBreak = !orders_dat::CanBeInterrupted[unit->orderQueueTail->orderId] && (unit->orderQueueTail->orderId != OrderId::BuildingLiftoff); if(!bLoopBreak) removeOrderFromUnitQueue(unit, unit->orderQueueTail); } //643D3: unit->performAnotherOrder( OrderId::BuildingLiftoff, coords.x, coords.y, NULL, 0 ); } //if( (unit->mainOrderId != OrderId::Die) ) //643E8 prepareForNextOrder(unit); if(unit->mainOrderId != OrderId::Die) { while(unit->orderQueueTail != NULL && unit->orderQueueTail->orderId == OrderId::BuildingLand) removeOrderFromUnitQueue(unit, unit->orderQueueTail); //6440A: unit->performAnotherOrder( OrderId::BuildingLand, unitTarget.pt.x, unitTarget.pt.y, unitTarget.unit, UnitId::None ); } //64422 unit->order(units_dat::ReturnToIdleOrder[unit->id],0,0,NULL,UnitId::None,false); } //if( !(unit->status & UnitStatus::GroundedBuilding) ) else //64450 if(unit->mainOrderState == 0) { //plan vertical movement toward ground function_004EB9C0(unit,unit->orderTarget.pt.x,unit->orderTarget.pt.y - unit->sprite->images.tail->verticalOffset); unit->mainOrderState = 1; } else if(unit->mainOrderState == 1) { //6448A if(unit->getMovableState() != 0) { int x,y; x = units_dat::BuildingDimensions[unit->id].x; y = units_dat::BuildingDimensions[unit->id].y; if(x<0) x+=1;if(y<0) y+=1; x /= 2;y /= 2; x = unit->orderTarget.pt.x - x; y = unit->orderTarget.pt.y - y; if(x<0) x+=31;if(y<0) y+=31; x /= 32;y /= 32; //check for units occupying the landing zone before //the final vertical movement started? u32 return_00473FB0 = function_00473FB0(unit,unit->playerId,x,y,unit->id,0,0,1,0); if(return_00473FB0 != 0) { //64504: //probably play "landing sequence interrupted" playBuildingLandSound(unit); if( unit->orderQueueHead != NULL && unit->orderQueueHead->orderId != OrderId::PlaceAddon ) removeOrderFromUnitQueue(unit, unit->orderQueueHead); unit->orderToIdle(); } else { //6452B: //use a AddFogMask() function after some coordinates calculations function_00469F60(unit,unit->orderTarget.pt.x,unit->orderTarget.pt.y); unit->building.landingTimer = 1; //plan movement again after latest updates function_004EB9C0(unit,unit->orderTarget.pt.x,unit->orderTarget.pt.y); if(unit->sprite->images.tail->paletteType == PaletteType::RLE_SHADOW) unit->sprite->images.tail->flags |= CImage_Flags::DontUpdate; unit->status |= UnitStatus::CanNotReceiveOrders; unit->flingyTopSpeed = 256; SetUnitMovementSpeed(unit,256); unit->mainOrderState = 2; } //if(return_00473FB0 == 0) } //if(unit->getMovableState()) != 0) } //if(unit->mainOrderState == 1) else if(unit->mainOrderState == 2) { bool bStopThere = false; //64587: if( !isUnitPositions2Equal(unit) ) { int someValue = scbw::getAngle( unit->sprite->position.x, unit->sprite->position.y, unit->nextTargetWaypoint.x, unit->nextTargetWaypoint.y ); bStopThere = ( (unit->velocityDirection1 - someValue) != 0 ); } //645B7 if(!bStopThere) { unit->sprite->playIscriptAnim(IscriptAnimation::Landing); unit->mainOrderState = 3; } } //if(unit->mainOrderState == 2) //there's no "else" here, mainOrderState = 2 can continue directly //into mainOrderState = 3 if mainOrderState was updated if(unit->mainOrderState == 3) { //645C7: //orderSignal is set by IScript animation if( (unit->getMovableState() != 0) && (unit->orderSignal & 0x10) ) { CUnit* addon; unit->orderSignal -= 0x10; //use a SetFogMask() function after some coordinates preparation function_00469EC0(unit,unit->orderTarget.pt.x,unit->orderTarget.pt.y); //recalculate position and update effect on //surroundings? function_0046A560(unit); //toggle pathing-related stuff to prepare //to no longer use pathing function_004634E0(unit); unit->sprite->elevationLevel = 4; setUnitPathing(unit,0); scbw::setUnitPosition(unit,unit->orderTarget.pt.x,unit->orderTarget.pt.y); //maybe update orders targetting the unit, //set repulse for units in surroundings,and //some others things? function_0046A5A0(unit); //maybe the landing unit would get excluded from multi-units selection //if that could happen in normal Starcraft gameplay?That may be what //this function do. if(unit->sprite->flags & CSprite_Flags::Selected && *clientSelectionCount > 1) function_004C3B40(unit); //64648 //change the verticalOffset of images besides shadow to 0 function_00498150(unit->sprite, 0); if(unit->sprite->images.tail->paletteType == PaletteType::RLE_SHADOW) unit->sprite->images.tail->flags &= ~CImage_Flags::DontUpdate; //probably what display the landing dust function_004997E0(unit->sprite); scbw::refreshConsole(); //crush units that managed to get unmovable there //(tanks in siege, burrowed zerg) function_00464300(unit); if(unit->orderQueueHead != NULL) { bool bGotMoveOrder; if( unit->orderQueueHead->orderId == OrderId::Move || unit->orderQueueHead->orderId == OrderId::Follow ) bGotMoveOrder = true; else { bGotMoveOrder = false; //6468F COrder* order = unit->orderQueueHead; if(order->orderId != OrderId::PlaceAddon) order = NULL; while(unit->orderQueueTail != order) removeOrderFromUnitQueue(unit, unit->orderQueueTail); //646AF if(unit->orderQueueHead == NULL) unit->orderComputerCL(units_dat::ReturnToIdleOrder[unit->id]); } if(bGotMoveOrder) //646C7 //this cause the landed building to immediately take off again to //execute the queued move/follow order function_00474760(unit, unit->orderQueueHead, OrderId::BuildingLiftoff); } //if(unit->orderQueueHead != NULL) //646CE //some units iterations, idle orders affectations, //and unknown order assignment? //maybe affect another selected unit depending on //attempt at giving order? function_00463640(unit); actUnitReturnToIdle(unit); addon = connectAddonCheck(unit); if(addon != NULL) completeAddon(unit, addon); //646EC if(*IS_PLACING_BUILDING) { placebuildingProc(); //add the last minute occupation info //of landing building to update an //ongoing attempt to choose a building //or landing location? if( !function_0048DDA0() ) { refreshLayer3And4(); //refresh various stuff, including //buttonset, dialogs... function_0048E310(); } } } //if( (unit->getMovableState() != 0) && (unit->orderSignal & 0x10) ) } //if(unit->mainOrderState == 3) } //void orders_BuildingLand(CUnit* unit) ; void orders_BuildingLiftoff(CUnit* unit) { if( (unit->status & UnitStatus::GroundedBuilding) && (units_dat::BaseProperty[unit->id] & UnitProperty::FlyingBuilding) ) { //649D5 if(unit->building.addon != NULL) disconnectFromAddOn(unit); if(unit->isFactory()) unit->rally.unit = unit; //update globally known position and may //remove repulse tile if no longer needed function_0046A560(unit); //disable GroundedBuilding status and //prepare to enable pathing? function_00463470(unit); //64A05 unit->sprite->elevationLevel = 12; setUnitPathing(unit,1); //maybe update orders targetting the unit, //set repulse for units in surroundings,and //some others things? function_0046A5A0(unit); if(unit->sprite->images.tail->paletteType == PaletteType::RLE_SHADOW) unit->sprite->images.tail->flags |= CImage_Flags::DontUpdate; //equivalent to 64A40 scbw::refreshConsole(); if( unit->sprite->position.x != unit->nextTargetWaypoint.x || unit->sprite->position.y - 42 != unit->nextTargetWaypoint.y ) { //64A76 unit->nextTargetWaypoint.x = unit->sprite->position.x; unit->nextTargetWaypoint.y = unit->sprite->position.y - 42; } //64A7E //probably update things related to creep since //there may be some under or around an infested //command center, return value unused if(unit->id == UnitId::ZergInfestedCommandCenter) function_0047DF90(unit); if(*IS_PLACING_BUILDING) placebuildingProc(); unit->mainOrderId = OrderId::Liftoff; } //GroundedBuilding && FlyingBuilding else { //64AA2 if(unit->orderQueueHead == NULL) unit->order(units_dat::ReturnToIdleOrder[unit->id], 0, 0, NULL, UnitId::None, 0); actUnitReturnToIdle(unit); } } //void orders_BuildingLiftoff(CUnit* unit) ; } //hooks //-------- Helper function definitions. Do NOT modify! --------// namespace { const u32 Func_SetUnitPathing = 0x00401360; void setUnitPathing(CUnit* unit, u8 unkPathRelated) { __asm { PUSHAD MOV AL, unkPathRelated MOV ECX, unit CALL Func_SetUnitPathing POPAD } } ; //Equivalent to function @ 0x00402160 bool isUnitPositions2Equal(CUnit* unit) { return ( unit->nextTargetWaypoint.x == unit->position.x && unit->nextTargetWaypoint.y == unit->position.y ); } ; const u32 Func_ConnectAddonCheck = 0x004404A0; CUnit* connectAddonCheck(CUnit* unit) { CUnit* found_addon; __asm { PUSHAD MOV ESI, unit CALL Func_ConnectAddonCheck MOV found_addon, EAX POPAD } return found_addon; } ; const u32 Func_Sub463470 = 0x00463470; void function_00463470(CUnit* unit) { __asm { PUSHAD MOV EAX, unit CALL Func_Sub463470 POPAD } } ; const u32 Func_Sub4634E0 = 0x004634E0; void function_004634E0(CUnit* unit) { __asm { PUSHAD MOV EAX, unit CALL Func_Sub4634E0 POPAD } } ; const u32 Func_Sub463640 = 0x00463640; void function_00463640(CUnit* unit) { __asm { PUSHAD MOV EAX, unit CALL Func_Sub463640 POPAD } } ; const u32 Func_CompleteAddon = 0x00463D50; void completeAddon(CUnit* unit, CUnit* addon) { __asm { PUSHAD MOV EDI, unit MOV EAX, addon CALL Func_CompleteAddon POPAD } } ; const u32 Func_Sub464300 = 0x00464300; void function_00464300(CUnit* unit) { __asm { PUSHAD MOV ECX, unit CALL Func_Sub464300 POPAD } } ; const u32 Func_Sub464930 = 0x00464930; void disconnectFromAddOn(CUnit* unit) { __asm { PUSHAD MOV EAX, unit CALL Func_Sub464930 POPAD } } ; const u32 Func_Sub469EC0 = 0x00469EC0; void function_00469EC0(CUnit* unit, int x, int y) { __asm { PUSHAD MOV EAX, unit PUSH y PUSH x CALL Func_Sub469EC0 POPAD } } ; const u32 Func_Sub469F60 = 0x00469F60; void function_00469F60(CUnit* unit, int x, int y) { __asm { PUSHAD MOV EAX, unit PUSH y PUSH x CALL Func_Sub469F60 POPAD } } ; const u32 Func_Sub46A560 = 0x0046A560; void function_0046A560(CUnit* unit) { __asm { PUSHAD MOV EAX, unit CALL Func_Sub46A560 POPAD } } ; const u32 Func_Sub46A5A0 = 0x0046A5A0; void function_0046A5A0(CUnit* unit) { __asm { PUSHAD MOV EAX, unit CALL Func_Sub46A5A0 POPAD } } ; const u32 Func_Sub473FB0 = 0x00473FB0; u32 function_00473FB0(CUnit* unit, u8 playerId, int x, int y, u16 unitId, u8 unk1, u8 unk2, u8 unk3, u8 unk4 ) { u32 return_value; __asm { PUSHAD MOVZX EAX, unk4 /*28*/ PUSH EAX MOVZX EAX, unk3 /*24*/ PUSH EAX MOVZX EAX, unk2 /*20*/ PUSH EAX MOVZX EAX, unk1 /*1C*/ PUSH EAX MOVZX EAX, unitId /*18*/ PUSH EAX PUSH y /*14*/ PUSH x /*10*/ MOVZX EAX, playerId /*0C*/ PUSH EAX PUSH unit /*08*/ CALL Func_Sub473FB0 MOV return_value, EAX POPAD } return return_value; } ; const u32 Func_removeOrderFromUnitQueue = 0x004742D0; void removeOrderFromUnitQueue(CUnit* unit, COrder* order) { __asm { PUSHAD MOV ECX, unit MOV EAX, order CALL Func_removeOrderFromUnitQueue POPAD } } ; const u32 Func_Sub474760 = 0x00474760; void function_00474760(CUnit* unit, COrder* order, u8 orderId) { __asm { PUSHAD MOV ESI, unit MOV EDI, order MOV BL, orderId CALL Func_Sub474760 POPAD } } ; const u32 Func_ActUnitReturnToIdle = 0x00475420; void actUnitReturnToIdle(CUnit* unit) { __asm { PUSHAD MOV EAX, unit CALL Func_ActUnitReturnToIdle POPAD } } ; const u32 Func_Sub47DF90 = 0x0047DF90; bool function_0047DF90(CUnit* unit) { Bool32 pre_return_value; __asm { PUSHAD PUSH unit CALL Func_Sub47DF90 MOV pre_return_value, EAX POPAD } return (pre_return_value != 0); } ; const u32 Func_RefreshLayer3And4 = 0x0048D9A0; void refreshLayer3And4() { __asm { PUSHAD CALL Func_RefreshLayer3And4 POPAD } } ; const u32 Func_Sub48DDA0 = 0x0048DDA0; bool function_0048DDA0() { Bool32 pre_return_value; __asm { PUSHAD CALL Func_Sub48DDA0 MOV pre_return_value, EAX POPAD } return (pre_return_value != 0); } ; const u32 Func_Sub48E310 = 0x0048E310; void function_0048E310() { __asm { PUSHAD CALL Func_Sub48E310 POPAD } } ; const u32 Func_PracebuildingProc = 0x0048E6E0; void placebuildingProc() { __asm { PUSHAD CALL Func_PracebuildingProc POPAD } } ; const u32 Func_PlayBuildingLandSound = 0x0048F5A0; void playBuildingLandSound(CUnit* unit) { __asm { PUSHAD MOV EAX, unit CALL Func_PlayBuildingLandSound POPAD } } ; const u32 Func_SetUnitMovementSpeed = 0x004951C0; void SetUnitMovementSpeed(CUnit* unit, u32 newSpeed) { __asm { PUSHAD MOV EAX, unit MOV EDX, newSpeed CALL Func_SetUnitMovementSpeed POPAD } } ; const u32 Func_Sub498150 = 0x00498150; void function_00498150(CSprite* sprite, u8 newVerticalOffset) { __asm { PUSHAD MOV EAX, sprite MOV CL, newVerticalOffset CALL Func_Sub498150 POPAD } } ; const u32 Func_Sub4997E0 = 0x004997E0; void function_004997E0(CSprite* sprite) { __asm { PUSHAD MOV EAX, sprite CALL Func_Sub4997E0 POPAD } } ; const u32 Func_Sub4C3B40 = 0x004C3B40; void function_004C3B40(CUnit* unit) { __asm { PUSHAD MOV EDX, unit CALL Func_Sub4C3B40 POPAD } } ; const u32 Func_Sub4EB9C0 = 0x004EB9C0; bool function_004EB9C0(CUnit* unit, int x, int y) { static Bool32 bPreResult; __asm { PUSHAD MOV EDX, unit MOV ECX, x MOV EAX, y CALL Func_Sub4EB9C0 MOV bPreResult, EAX POPAD } return (bPreResult != 0); } ; } //Unnamed namespace //End of helper functions